class DatabaseClient(BaseDatabaseClient): executable_name = 'bash' port_range = (8097, 9015) def start_server_thread(self): self.server_thread = LiveServerThread('localhost', range(*self.port_range), _StaticFilesHandler) self.server_thread.daemon = True self.server_thread.start() # Wait for the live server to be ready self.server_thread.is_ready.wait() if self.server_thread.error: # Clean up behind ourselves, since tearDownClass won't get called in # case of errors. self.stop_server_thread() raise self.server_thread.error return 'http://%s:%s' % (self.server_thread.host, self.server_thread.port) def stop_server_thread(self): # There may not be a 'server_thread' attribute if setUpClass() for some # reasons has raised an exception. if hasattr(self, 'server_thread'): # Terminate the live server's thread self.server_thread.terminate() self.server_thread.join() def runshell(self): resty_path = os.path.join(os.path.dirname(__file__), "exec", "resty") args = [self.executable_name, "--init-file", resty_path] cname = self.connection.settings_dict['NAME'] if cname.startswith(LocalApiAdapter.SPECIAL_URL): cname = cname.replace(LocalApiAdapter.SPECIAL_URL, self.start_server_thread()) cname = cname.rstrip("/") + "*" envs = os.environ.copy() envs.update( dict(_EXTRA_CURL_AUTH=self.get_middleware_curl_args(), _resty_host=cname)) self.execute_subprocess(args=args, env=envs) self.stop_server_thread() def execute_subprocess(self, args, env): subprocess.call(args, env=env) # pragma: no cover def get_middleware_curl_args(self): """ return the curl extra args to authorize ourselve to the api :return: """ return ""
class Command(BaseCommand): help = ''' test command, should be deleted in the future ''' def handle(self, *args, **options): try: conn = connections['default'] conn.creation.create_test_db(2, autoclobber=False, keepdb=False, serialize=conn.settings_dict['TEST'].get('SERIALIZE', True)) conn.inc_thread_sharing() self.connections_override = {} self.connections_override[conn.alias] = conn fixt = ['mainsite/fixtures/initial-data.json'] call_command('loaddata', *fixt, **{'verbosity': 2, 'database': conn.alias}) self.server_thread = LiveServerThread('127.0.0.1', StaticFilesHandler, self.connections_override, 8090) self.server_thread.daemon = True self.server_thread.start() self.server_thread.is_ready.wait() if self.server_thread.error: self.server_thread.terminate() for conn in self.connections_override.values(): conn.dec_thread_sharing() conn.close() raise self.server_thread.error time.sleep(120) except Exception as e: print(e) self.server_thread.terminate() for conn in self.connections_override.values(): conn.dec_thread_sharing() conn.close()
class LiveServer: """The liveserver fixture This is the object that the ``live_server`` fixture returns. The ``live_server`` fixture handles creation and stopping. """ def __init__(self, addr): from django.db import connections from django.test.testcases import LiveServerThread from django.test.utils import modify_settings connections_override = {} for conn in connections.all(): # If using in-memory sqlite databases, pass the connections to # the server thread. if (conn.settings_dict["ENGINE"] == "django.db.backends.sqlite3" and conn.settings_dict["NAME"] == ":memory:"): # Explicitly enable thread-shareability for this connection conn.allow_thread_sharing = True connections_override[conn.alias] = conn liveserver_kwargs = {"connections_override": connections_override} from django.conf import settings if "django.contrib.staticfiles" in settings.INSTALLED_APPS: from django.contrib.staticfiles.handlers import StaticFilesHandler liveserver_kwargs["static_handler"] = StaticFilesHandler else: from django.test.testcases import _StaticFilesHandler liveserver_kwargs["static_handler"] = _StaticFilesHandler try: host, port = addr.split(":") except ValueError: host = addr else: liveserver_kwargs["port"] = int(port) self.thread = LiveServerThread(host, **liveserver_kwargs) self._live_server_modified_settings = modify_settings( ALLOWED_HOSTS={"append": host}) self.thread.daemon = True self.thread.start() self.thread.is_ready.wait() if self.thread.error: raise self.thread.error def stop(self): """Stop the server""" self.thread.terminate() self.thread.join() @property def url(self): return "http://{}:{}".format(self.thread.host, self.thread.port) def __str__(self): return self.url def __add__(self, other): return "{}{}".format(self, other) def __repr__(self): return "<LiveServer listening at %s>" % self.url
class LiveServer(object): """The liveserver fixture This is the object that the ``live_server`` fixture returns. The ``live_server`` fixture handles creation and stopping. """ def __init__(self, addr): import django from django.db import connections from django.test.testcases import LiveServerThread from django.test.utils import modify_settings connections_override = {} for conn in connections.all(): # If using in-memory sqlite databases, pass the connections to # the server thread. if (conn.settings_dict['ENGINE'] == 'django.db.backends.sqlite3' and conn.settings_dict['NAME'] == ':memory:'): # Explicitly enable thread-shareability for this connection conn.allow_thread_sharing = True connections_override[conn.alias] = conn liveserver_kwargs = {'connections_override': connections_override} from django.conf import settings if 'django.contrib.staticfiles' in settings.INSTALLED_APPS: from django.contrib.staticfiles.handlers import StaticFilesHandler liveserver_kwargs['static_handler'] = StaticFilesHandler else: from django.test.testcases import _StaticFilesHandler liveserver_kwargs['static_handler'] = _StaticFilesHandler if django.VERSION < (1, 11): host, possible_ports = parse_addr(addr) self.thread = LiveServerThread(host, possible_ports, **liveserver_kwargs) else: try: host, port = addr.split(':') except ValueError: host = addr else: liveserver_kwargs['port'] = int(port) self.thread = LiveServerThread(host, **liveserver_kwargs) self._live_server_modified_settings = modify_settings( ALLOWED_HOSTS={'append': host}, ) self._live_server_modified_settings.enable() self.thread.daemon = True self.thread.start() self.thread.is_ready.wait() if self.thread.error: raise self.thread.error def stop(self): """Stop the server""" self.thread.terminate() self.thread.join() self._live_server_modified_settings.disable() @property def url(self): return 'http://%s:%s' % (self.thread.host, self.thread.port) if sys.version_info < (3, 0): def __unicode__(self): return self.url def __add__(self, other): return unicode(self) + other # noqa: pyflakes on python3 else: def __str__(self): return self.url def __add__(self, other): return str(self) + other def __repr__(self): return '<LiveServer listening at %s>' % self.url