Пример #1
0
    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(object):
    def __init__(self, host, possible_ports):

        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

        self.thread = LiveServerThread(host, possible_ports,
                                       connections_override)
        self.thread.daemon = True
        self.thread.start()

        self.thread.is_ready.wait()

        if self.thread.error:
            raise self.thread.error

    def __unicode__(self):
        return 'http://%s:%s' % (self.thread.host, self.thread.port)

    def __repr__(self):
        return '<LiveServer listening at %s>' % unicode(self)

    def __add__(self, other):
        # Support string concatenation
        return unicode(self) + other
Пример #3
0
class LiveServer(object):
    def __init__(self, host, possible_ports):

        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

        self.thread = LiveServerThread(host, possible_ports, connections_override)
        self.thread.daemon = True
        self.thread.start()

        self.thread.is_ready.wait()

        if self.thread.error:
            raise self.thread.error

    def __unicode__(self):
        return 'http://%s:%s' % (self.thread.host, self.thread.port)

    def __repr__(self):
        return '<LiveServer listenting at %s>' % unicode(self)

    def __add__(self, other):
        # Support string concatenation
        return unicode(self) + other
    def __init__(self, addr):
        try:
            from django.test.testcases import LiveServerThread
        except ImportError:
            pytest.skip('live_server tests not supported in Django < 1.4')
        from django.db import connections

        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}
        try:
            from django.test.testcases import _StaticFilesHandler
            liveserver_kwargs['static_handler'] = _StaticFilesHandler
        except ImportError:
            pass

        host, possible_ports = parse_addr(addr)
        self.thread = LiveServerThread(host, possible_ports,
                                       **liveserver_kwargs)
        self.thread.daemon = True
        self.thread.start()
        self.thread.is_ready.wait()

        if self.thread.error:
            raise self.thread.error
Пример #5
0
class LiveServer(object):
    """The liveserver fixture

    This is the object which is returned to the actual user when they
    request the ``live_server`` fixture.  The fixture handles creation
    and stopping however.
    """
    def __init__(self, addr):
        try:
            from django.test.testcases import LiveServerThread
        except ImportError:
            pytest.skip('live_server tests not supported in Django < 1.4')
        from django.db import connections

        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

        host, possible_ports = parse_addr(addr)
        self.thread = LiveServerThread(host, possible_ports,
                                       connections_override)
        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.join()

    @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
    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
class LiveServer(object):
    """The liveserver fixture

    This is the object which is returned to the actual user when they
    request the ``live_server`` fixture.  The fixture handles creation
    and stopping however.
    """

    def __init__(self, addr):
        try:
            from django.test.testcases import LiveServerThread
        except ImportError:
            pytest.skip('live_server tests not supported in Django < 1.4')
        from django.db import connections

        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

        host, possible_ports = parse_addr(addr)
        self.thread = LiveServerThread(host, possible_ports,
                                       connections_override)
        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.join()

    @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
    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
 def handle(self, *args, **options):
     host = "0.0.0.0"
     port = options["port"]
     lst = LiveServerThread(
         host=host,
         possible_ports=[port],
         static_handler=options['static_handler']
     )
     self.stdout.write(
         'Starting live server on http://%s:%s...' % (host, port)
     )
     lst.run()
     raise lst.error
Пример #8
0
    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.thread.daemon = True
        self.thread.start()
        self.thread.is_ready.wait()

        if self.thread.error:
            raise self.thread.error
Пример #9
0
class Server(object):
    """A silenced, lightweight and simple django's builtin server so
    that lettuce can be used with selenium, webdriver, windmill or any
    browser tool"""

    def __init__(self, address='0.0.0.0', port=None):
        self.port = int(port or getattr(settings, 'LETTUCE_SERVER_PORT', 8000))
        self.address = unicode(address)
        connections_override = {}
        for conn in connections.all():
            if (conn.settings_dict['ENGINE'] == 'django.db.backends.sqlite3' and conn.settings_dict['NAME'] == ':memory:'):
                conn.allow_thread_sharing = True
                connections_override[conn.alias] = conn
        self._actual_server = LiveServerThread(self.address, [self.port], connections_override)

    def start(self):
        """Starts the webserver thread, and waits it to be available"""
        call_hook('before', 'runserver', self._actual_server)
        self._actual_server.daemon = True
        self._actual_server.start()
        self._actual_server.is_ready.wait()
        if self._actual_server.error:
            raise self._actual_server.error
        addrport = self.address, self.port
#        if not self._actual_server.is_alive():
#            raise LettuceServerException(
#                'Lettuce could not run the builtin Django server at %s:%d"\n'
#                'maybe you forgot a "runserver" instance running ?\n\n'
#                'well if you really do not want lettuce to run the server '
#                'for you, then just run:\n\n'
#                'python manage.py --no-server' % addrport,
#            )

        print "Django's builtin server is running at %s:%d" % addrport

    def stop(self, fail=False):
        if self._actual_server:
            self._actual_server.join()

        code = int(fail)
        call_hook('after', 'runserver', self._actual_server)
        return sys.exit(code)

    def url(self, url=""):
        base_url = "http://%s" % ThreadedServer.get_real_address(self.address)

        if self.port is not 80:
            base_url += ':%d' % self.port

        return urlparse.urljoin(base_url, url)
Пример #10
0
    def start_server_thread(self):
        self.server_thread = LiveServerThread('localhost', _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 server_thread_start(self):
        try:
            conn = connections[self._instance.connection_alias]
            conn.creation.create_test_db(
                self._instance.verbosity,
                autoclobber=False,
                keepdb=False,
                serialize=conn.settings_dict['TEST'].get('SERIALIZE', True))
            conn.inc_thread_sharing()
            self._instance.connections_override[conn.alias] = conn
            if self._instance.fixtures:
                call_command(
                    'loaddata', *self._instance.fixtures, **{
                        'verbosity': self._instance.verbosity,
                        'database': conn.alias
                    })

            self._instance.server_thread = LiveServerThread(
                self._instance.host, StaticFilesHandler,
                self._instance.connections_override, self._instance.port)
            self._instance.server_thread.daemon = True
            self._instance.server_thread.start()
            self._instance.server_thread.is_ready.wait()

            if self._instance.server_thread.error:
                self.server_thread_stop()
                raise self._instance.server_thread.error

        except Exception as e:
            print(e)
            self.server_thread_stop()
Пример #12
0
    def __init__(self, addr):
        from django.db import connections
        from django.test.testcases import LiveServerThread

        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

        host, possible_ports = parse_addr(addr)
        self.thread = LiveServerThread(host, possible_ports,
                                       **liveserver_kwargs)
        self.thread.daemon = True
        self.thread.start()
        self.thread.is_ready.wait()

        if self.thread.error:
            raise self.thread.error
Пример #13
0
    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:
            host = addr
            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
Пример #14
0
 def __init__(self, address='0.0.0.0', port=None):
     self.port = int(port or getattr(settings, 'LETTUCE_SERVER_PORT', 8000))
     self.address = unicode(address)
     connections_override = {}
     for conn in connections.all():
         if (conn.settings_dict['ENGINE'] == 'django.db.backends.sqlite3' and conn.settings_dict['NAME'] == ':memory:'):
             conn.allow_thread_sharing = True
             connections_override[conn.alias] = conn
     self._actual_server = LiveServerThread(self.address, [self.port], connections_override)
Пример #15
0
    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:
            host = addr
            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 handle(self, *args, **options):
		address = os.environ.get('DJANGO_LIVE_TEST_SERVER_ADDRESS')

		# Live server will be binded to all hosts if user haven't defined hostname
		if re.match(address, '^:'):
			address = '0.0.0.0%s' % address

		try:
			host, ports = address.split(':')
		except ValueError:
			raise CommandError('Live server port not defined')

		# Get testcase class by parsing import string
		try:
			test_class = options['testcase'].split('.')[-1]
			module = __import__(('.').join(options['testcase'].split('.')[:-1]), fromlist=test_class)
		except AttributeError:
			raise CommandError('Wrong test case import path specified in --testcase option')

		TestCase = getattr(module, test_class)

		# Prepare DB connection for live server
		connections_override = {}
		
		for C in connections.all():
			if (C.settings_dict['ENGINE'].rsplit('.', 1)[-1] in ('sqlite3', 'spatialite') and C.settings_dict['NAME'] == ':memory:'):
				# Explicitly enable thread-shareability for this connection
				C.allow_thread_sharing = True
				connections_override[C.alias] = C

		# Setup DB and fixtures
		db_name = connection.creation.create_test_db(verbosity=False, autoclobber=False)

		if hasattr(TestCase, 'fixtures'):
			call_command('loaddata', *TestCase.fixtures, **{'verbosity': False})

		# Start live server. No need to parse ports ranges for screen capturing
		# as it served by just one server.
		server = LiveServerThread(host, map(lambda P: int(P), re.split('\-|,', ports)), connections_override)

		server.setDaemon(True)
		server.start()
		server.is_ready.wait()

		# Init Ghost driver and capture page that will be tested
		test = TestCase('test_%s' % options['name'])

		test.init_driver()
		test.server_thread = server

		# TestCase.screenshot_<name> is the screenshot asserted in TestCase.test_<name>
		getattr(test, 'screenshot_%s' % options['name'])(settings.SCREENSHOT_ROOT)

		# Clean up test environment
		test.driver.exit()
		connection.creation.destroy_test_db(db_name)
		server.join()
Пример #17
0
    def __init__(self, host, possible_ports):

        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

        self.thread = LiveServerThread(host, possible_ports,
                                       connections_override)
        self.thread.daemon = True
        self.thread.start()

        self.thread.is_ready.wait()

        if self.thread.error:
            raise self.thread.error
Пример #18
0
    def __init__(self, addr):
        from django.db import connections
        from django.test.testcases import LiveServerThread

        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
                and get_django_version() >= (1, 7)):
            from django.contrib.staticfiles.handlers import (StaticFilesHandler
                                                             )
            liveserver_kwargs['static_handler'] = StaticFilesHandler
        else:
            try:
                from django.test.testcases import _StaticFilesHandler
            except ImportError:
                pass
            else:
                liveserver_kwargs['static_handler'] = _StaticFilesHandler

        host, possible_ports = parse_addr(addr)
        self.thread = LiveServerThread(host, possible_ports,
                                       **liveserver_kwargs)
        self.thread.daemon = True
        self.thread.start()
        self.thread.is_ready.wait()

        if self.thread.error:
            raise self.thread.error
Пример #19
0
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 ""
Пример #20
0
    def __init__(self, host, possible_ports):

        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

        self.thread = LiveServerThread(host, possible_ports, connections_override)
        self.thread.daemon = True
        self.thread.start()

        self.thread.is_ready.wait()

        if self.thread.error:
            raise self.thread.error
Пример #21
0
class LiveServer(object):
    """The liveserver fixture

    This is the object which is returned to the actual user when they
    request the ``live_server`` fixture.  The fixture handles creation
    and stopping however.
    """

    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:
            host = addr
            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"""
        # .terminate() was added in Django 1.7
        terminate = getattr(self.thread, "terminate", lambda: None)
        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
Пример #22
0
class LiveServer(object):
    """The liveserver fixture

    This is the object which is returned to the actual user when they
    request the ``live_server`` fixture.  The fixture handles creation
    and stopping however.
    """
    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:
            host = addr
            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"""
        # .terminate() was added in Django 1.7
        terminate = getattr(self.thread, 'terminate', lambda: None)
        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
Пример #23
0
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
Пример #24
0
def start_django():
    server = LiveServerThread("localhost", SAUCE_PORTS, _StaticFilesHandler)
    server.daemon = True
    server.start()
    return server
Пример #25
0
class LiveServer(object):
    """The liveserver fixture

    This is the object which is returned to the actual user when they
    request the ``live_server`` fixture.  The fixture handles creation
    and stopping however.
    """

    def __init__(self, addr):
        try:
            from django.test.testcases import LiveServerThread
        except ImportError:
            pytest.skip('live_server tests not supported in Django < 1.4')
        from django.db import connections

        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 and
                get_django_version() >= (1, 7)):
            from django.contrib.staticfiles.handlers import (
                StaticFilesHandler)
            liveserver_kwargs['static_handler'] = StaticFilesHandler
        else:
            try:
                from django.test.testcases import _StaticFilesHandler
            except ImportError:
                pass
            else:
                liveserver_kwargs['static_handler'] = _StaticFilesHandler

        host, possible_ports = parse_addr(addr)
        self.thread = LiveServerThread(host, possible_ports,
                                       **liveserver_kwargs)
        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"""
        # .terminate() was added in Django 1.7
        terminate = getattr(self.thread, 'terminate', lambda: None)
        terminate()
        self.thread.join()

    @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