Beispiel #1
0
    def setUpClass(cls):
        test_runner = DjangoTestSuiteRunner(interactive=False, verbosity=1)
        test_db = test_runner.setup_databases()
        load_fixture()

        setattr(cls, "test_runner", test_runner)
        setattr(cls, "test_db", test_db)
    def _tests_1_7(self):
        """
        Fire up the Django test suite developed for version 1.7 and up
        """
        INSTALLED_APPS, settings_test = self.get_custom_settings()

        settings.configure(
            DEBUG=True,
            DATABASES=self.get_database(),
            MIDDLEWARE_CLASSES=(
                "django.middleware.common.CommonMiddleware",
                "django.middleware.csrf.CsrfViewMiddleware",
            ),
            INSTALLED_APPS=self.INSTALLED_APPS + INSTALLED_APPS + self.apps,
            **settings_test
        )

        try:
            # Django <= 1.8
            from django.test.simple import DjangoTestSuiteRunner

            test_runner = DjangoTestSuiteRunner(verbosity=1)
        except ImportError:
            # Django >= 1.8
            from django.test.runner import DiscoverRunner

            test_runner = DiscoverRunner(verbosity=1)

        import django

        django.setup()
        failures = test_runner.run_tests(self.apps, verbosity=1)
        if failures:
            sys.exit(failures)
Beispiel #3
0
def runtests():
    verbose_level = 1
    args = sys.argv[1:]

    if '-v' in args:
        index = args.index('-v')
        _ = args.pop(index)
        verbose_level = int(args.pop(index))

    if args:
        test_labels = ["model_mommy.%s" % arg for arg in args]
    else:
        test_labels = ['model_mommy']

    try:
        from django.test.simple import run_tests

        result = run_tests(test_labels, verbose_level, True)
        sys.exit(result)
    except ImportError:
        from django.test.simple import DjangoTestSuiteRunner

        test_suite = DjangoTestSuiteRunner(verbose_level, True)
        result = test_suite.run_tests(test_labels)
        sys.exit(result)
def run_tests(verbosity, *test_args):
    if not test_args:
        test_args = ['url_tracker']
    test_runner = DjangoTestSuiteRunner(verbosity=verbosity)
    num_failures = test_runner.run_tests(test_args)
    if num_failures:
        sys.exit(num_failures)
Beispiel #5
0
def runtests(*test_args):
    if not test_args:
        test_args = ['blog']

    runner = DjangoTestSuiteRunner(verbosity=1, interactive=True, failfast=False)
    failures = runner.run_tests(test_args)
    sys.exit(failures)
def _django_runner(request):
    """Create the django runner, internal to pytest-django

    This does important things like setting up the local memory email
    backend etc.

    XXX It is a little dodgy that this is an autouse fixture.  Perhaps
        an email fixture should be requested in order to be able to
        use the Django email machinery just like you need to request a
        db fixture for access to the Django database, etc.  But
        without duplicating a lot more of Django's test support code
        we need to follow this model.
    """
    if django_settings_is_configured():
        import django
        # Django >= 1.7: Call django.setup() to initialize Django
        setup = getattr(django, 'setup', lambda: None)
        setup()

        from django.test.simple import DjangoTestSuiteRunner

        runner = DjangoTestSuiteRunner(interactive=False)
        runner.setup_test_environment()
        request.addfinalizer(runner.teardown_test_environment)
        return runner
Beispiel #7
0
def run_tests(verbosity, *test_args):
    test_runner = DjangoTestSuiteRunner(verbosity=verbosity)
    if not test_args:
        test_args = ['oscar']
    num_failures = test_runner.run_tests(test_args)
    if num_failures:
        sys.exit(num_failures)
Beispiel #8
0
def teardown_database(real_server):
  '''
  Destroys test database
  '''
  logger.info("Destroying test database.")
  
  DjangoTestSuiteRunner.teardown_databases(world.test_runner, world.creaded_db)
Beispiel #9
0
def get_runner(config):
    runner = DjangoTestSuiteRunner(interactive=False)

    if config.option.no_db:
        def cursor_wrapper_exception(*args, **kwargs):
            raise RuntimeError('No database access is allowed since --no-db was used!')

        def setup_databases():
            # Monkey patch CursorWrapper to warn against database usage
            django.db.backends.util.CursorWrapper = cursor_wrapper_exception

        def teardown_databases(db_config):
            pass

        runner.setup_databases = setup_databases
        runner.teardown_databases = teardown_databases

    elif config.option.reuse_db:

        if not config.option.create_db:
            monkey_patch_creation_for_db_reuse()

        # Leave the database for the next test run
        runner.teardown_databases = lambda db_config: None

    return runner
Beispiel #10
0
    def test_setup_aliased_databases(self):
        from django.db.backends.dummy.base import DatabaseCreation

        runner = DjangoTestSuiteRunner(verbosity=0)
        old_db_connections = db.connections
        old_destroy_test_db = DatabaseCreation.destroy_test_db
        old_create_test_db = DatabaseCreation.create_test_db
        try:
            destroyed_names = []
            DatabaseCreation.destroy_test_db = lambda self, old_database_name, verbosity=1: destroyed_names.append(old_database_name)
            DatabaseCreation.create_test_db = lambda self, verbosity=1, autoclobber=False: self._get_test_db_name()

            db.connections = db.ConnectionHandler({
                'default': {
                    'ENGINE': 'django.db.backends.dummy',
                    'NAME': 'dbname',
                },
                'other': {
                    'ENGINE': 'django.db.backends.dummy',
                    'NAME': 'dbname',
                }
            })

            old_config = runner.setup_databases()
            runner.teardown_databases(old_config)

            self.assertEqual(destroyed_names.count('dbname'), 1)
        finally:
            DatabaseCreation.create_test_db = old_create_test_db
            DatabaseCreation.destroy_test_db = old_destroy_test_db
            db.connections = old_db_connections
def test_runner_with_coverage(test_labels, verbosity=1, interactive=True,
                              failfast=None, extra_tests=[]):
    """
    Custom test runner.  Follows the django.test.simple.run_tests() interface.
    """
    # Start code coverage before anything else if necessary
    if hasattr(settings, 'COVERAGE_MODULES'):
        cov = coverage.coverage()
        cov.use_cache(0)  # Do not cache any of the coverage.py stuff
        cov.start()

    test_runner = DjangoTestSuiteRunner(verbosity=verbosity,
                                        interactive=interactive,
                                        failfast=failfast)
    test_results = test_runner.run_tests(test_labels, extra_tests=extra_tests)

    # Stop code coverage after tests have completed
    if hasattr(settings, 'COVERAGE_MODULES'):
        cov.stop()

    print ''
    print '-------------------------------------------------------------------'
    print ' Unit Test Code Coverage Results'
    print '-------------------------------------------------------------------'
    coverage_modules = []
    for module in settings.COVERAGE_MODULES:
        coverage_modules.append(
          __import__(module, globals(), locals(), [''])
        )
    cov.report(coverage_modules, show_missing=1)
    cov.html_report(coverage_modules, directory='coverage_report')
    print '-------------------------------------------------------------------'

    return test_results
Beispiel #12
0
    def handle(self, *args, **options):
        USE_SOUTH = getattr(settings, "SOUTH_TESTS_MIGRATE", True)
        try:
            if USE_SOUTH:
                from south.management.commands import patch_for_test_db_setup
                patch_for_test_db_setup()
        except:
            USE_SOUTH = False

        self._test_runner = DjangoTestSuiteRunner(interactive=False)
        DjangoTestSuiteRunner.setup_test_environment(self._test_runner)
        self._created_db = DjangoTestSuiteRunner.setup_databases(self._test_runner)
        call_command('syncdb', verbosity=0, interactive=False,)

        if USE_SOUTH:
            call_command('migrate', verbosity=0, interactive=False,)

        settings.DEBUG = options.get('debug', False)

        verbosity = int(options.get('verbosity', 4))
        apps_to_run = tuple(options.get('apps', '').split(","))
        apps_to_avoid = tuple(options.get('avoid_apps', '').split(","))
        run_server = not options.get('no_server', False)
        tags = options.get('tags', None)
        server = Server(port=options['port'])

        paths = self.get_paths(args, apps_to_run, apps_to_avoid)
        if run_server:
            try:
                server.start()
            except LettuceServerException, e:
                raise SystemExit(e)
Beispiel #13
0
def setup():
    global test_runner
    global old_config
    from django.test.simple import DjangoTestSuiteRunner
    test_runner = DjangoTestSuiteRunner()
    test_runner.setup_test_environment()
    old_config = test_runner.setup_databases()
Beispiel #14
0
    def setup_django(self):
        from django.conf import settings

        # If Django < 1.2
        if self.legacy_django:
            from django.db import connection
            from django.test.utils import setup_test_environment

            # Setup Django test environment
            setup_test_environment()

            # Create Django test database
            self.old_database_name = settings.DATABASE_NAME
            connection.creation.create_test_db(self.verbosity,
                                               autoclobber=True)
        # If Django >= 1.2
        else:
            from django.test.simple import DjangoTestSuiteRunner

            # Initialize Django tests runner
            runner = DjangoTestSuiteRunner(interactive=self.interactive,
                                           verbosity=self.verbosity)

            # Setup test environment
            runner.setup_test_environment()

            # Setup test databases
            self.old_config = runner.setup_databases()
            self.runner = runner
Beispiel #15
0
def teardown_database(actual_server):
	'''
	This will destroy your test database after all of your tests have executed.
	'''
	logger.info("Destroying the test database ...")
 
	DjangoTestSuiteRunner.teardown_databases(world.test_runner, world.created_db)
Beispiel #16
0
def main():
    settings.configure(
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
            }
        },
        ROOT_URLCONF='acme_challenge.urls',
        INSTALLED_APPS=(
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.sessions',
            'django.contrib.admin',
            'acme_challenge',)
    )
    
    django.setup()
    try:
        # Django <= 1.8
        from django.test.simple import DjangoTestSuiteRunner
        test_runner = DjangoTestSuiteRunner(verbosity=1)
    except ImportError:
        # Django >= 1.8
        from django.test.runner import DiscoverRunner
        test_runner = DiscoverRunner(verbosity=1)
        
    failures = test_runner.run_tests(['acme_challenge'])
    if failures:
        sys.exit(failures)
def runtests(*test_args):
    """Setup and run django-password-policies test suite.

    This still uses the old django.test.simple.DjangoTestSuiteRunner for
    compatibility reasons with older Django versions and because of the
    abstract base classes which shouldn't be considered as tests, but are
    discovered by the newer django.test.runner.DiscoverRunner.
    """
    os.environ['DJANGO_SETTINGS_MODULE'] = 'password_policies.tests.settings'

    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)

    try:
        django.setup()
    except AttributeError:
        # Access one setting to trigger the initialization of the settings as
        # workaround for older Django versions
        settings.INSTALLED_APPS

    try:
        from django.test.runner import DiscoverRunner
        potential_test_args = ['password_policies.tests']
    except ImportError:
        from django.test.simple import DjangoTestSuiteRunner
        test_runner = DjangoTestSuiteRunner(interactive=False)
        potential_test_args = ['password_policies']
    else:
        test_runner = DiscoverRunner(interactive=False)

    if not test_args:
        test_args = potential_test_args
    failures = test_runner.run_tests(test_args)
    sys.exit(bool(failures))
Beispiel #18
0
def run_tests():
    """
    Use the Django test runner to run the tests.
    """
    from django.test.simple import DjangoTestSuiteRunner
    runner = DjangoTestSuiteRunner(verbosity=2)
    runner.run_tests(None)
def runtests():

    from django.test.simple import DjangoTestSuiteRunner
    dtsr = DjangoTestSuiteRunner(verbosity=1,
                                    interactive=True, 
                                    failfast=False)
    failures = dtsr.run_tests(['django_unique_submission'])
    sys.exit(failures)
Beispiel #20
0
def run_tests(*test_args):
    from django.test.simple import DjangoTestSuiteRunner
    if not test_args:
        test_args = ['main']
    tests_runner = DjangoTestSuiteRunner(
        verbosity=1, interactive=True, failfast=False)
    failures = tests_runner.run_tests(test_args)
    sys.exit(failures)
Beispiel #21
0
def runtests(*test_args):
    test_args = test_args or ['testapp']
    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)
    runner = DjangoTestSuiteRunner(verbosity=1, interactive=True,
                                   failfast=False)
    failures = runner.run_tests(test_args)
    sys.exit(failures)
Beispiel #22
0
def runtests(*test_args):
    if not test_args:
        test_args = ['django_measurement']
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    runner = DjangoTestSuiteRunner(verbosity=1, interactive=True)
    failures = runner.run_tests(test_args)
    sys.exit(failures)
Beispiel #23
0
def runtests(*args):
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    testrunner = DjangoTestSuiteRunner()
    if not args:
        args = None
    failures = testrunner.run_tests(args)
    sys.exit(failures)
Beispiel #24
0
def setup_django_test_database():
    from django.test.simple import DjangoTestSuiteRunner
    from django.test.utils import setup_test_environment
    from south.management.commands import patch_for_test_db_setup
    runner = DjangoTestSuiteRunner(verbosity=0, failfast=False)
    patch_for_test_db_setup()
    setup_test_environment()
    return runner, runner.setup_databases()
def runtests(*args, **kwargs):
    dts = DjangoTestSuiteRunner(
            verbosity=kwargs.get('verbosity', 1),
            interactive=kwargs.get('interactive', False),
            failfast=kwargs.get('failfast')
    )
    failures = dts.run_tests(*args)
    sys.exit(failures)
Beispiel #26
0
def runtests(*test_args):
    if not test_args:
        test_args = ["dialogos"]
    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)
    runner = DjangoTestSuiteRunner(verbosity=1, interactive=True)
    failures = runner.run_tests(test_args)
    sys.exit(failures)
def runtests(*test_args):
    if not test_args:
        test_args = ["linkcheck"]
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    test_runner = DjangoTestSuiteRunner(verbosity=1, interactive=True)
    failures = test_runner.run_tests(test_args)
    sys.exit(failures)
Beispiel #28
0
def runtests(args=None):
    try:
        from django.test.simple import DjangoTestSuiteRunner
    except ImportError:
        from django.test import DjangoTestSuiteRunner
    test_runner = DjangoTestSuiteRunner(verbosity=1)
    failures = test_runner.run_tests(['census', ])
    sys.exit(failures)
def runtests(*test_args):
    if not test_args:
        test_args = ["tests"]
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    runner = DjangoTestSuiteRunner(verbosity=2, interactive=True, failfast=False)
    failures = runner.run_tests(test_args)
    sys.exit(failures)
Beispiel #30
0
def runtests(*test_args):
    if not test_args:
        test_args = ['pro', 'standard', 'ipn']
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    test_runner = DjangoTestSuiteRunner(verbosity=1)
    failures = test_runner.run_tests(test_args, verbosity=1, interactive=True)
    sys.exit(failures)
Beispiel #31
0
 def test_setup_databases(self):
     """
     Test that setup_databases() doesn't fail with dummy database backend.
     """
     runner = DjangoTestSuiteRunner(verbosity=0)
     old_db_connections = db.connections
     try:
         db.connections = db.ConnectionHandler({})
         old_config = runner.setup_databases()
         runner.teardown_databases(old_config)
     except Exception as e:
         self.fail("setup_databases/teardown_databases unexpectedly raised "
                   "an error: %s" % e)
     finally:
         db.connections = old_db_connections
Beispiel #32
0
    def _tests_1_2(self):
        """
        Fire up the Django test suite developed for version 1.2 and up
        """
        INSTALLED_APPS, settings_test = self.get_custom_settings()

        settings.configure(DEBUG=True,
                           DATABASES=self.get_database(),
                           INSTALLED_APPS=self.INSTALLED_APPS +
                           INSTALLED_APPS + self.apps,
                           **settings_test)

        from django.test.simple import DjangoTestSuiteRunner
        failures = DjangoTestSuiteRunner().run_tests(self.apps, verbosity=1)
        if failures:
            sys.exit(failures)
    def _new_tests(self):
        """
        Fire up the Django test suite developed for version 1.2
        """

        settings.configure(DEBUG=True,
                           DATABASES={
                               'default': {
                                   'ENGINE':
                                   'django.db.backends.sqlite3',
                                   'NAME':
                                   os.path.join(self.DIRNAME, 'database.db'),
                                   'USER':
                                   '',
                                   'PASSWORD':
                                   '',
                                   'HOST':
                                   '',
                                   'PORT':
                                   '',
                               }
                           },
                           INSTALLED_APPS=self.INSTALLED_APPS + self.apps,
                           MIDDLEWARE_CLASSES=self.MIDDLEWARE_CLASSES,
                           ROOT_URLCONF='helpdesk.tests.urls',
                           STATIC_URL='/static/',
                           TEMPLATES=self.TEMPLATES)

        # compatibility with django 1.8 downwards
        # see: http://stackoverflow.com/questions/3841725/how-to-launch-tests-for-django-reusable-app

        try:
            # Django >= 1.6
            from django.test.runner import DiscoverRunner
            test_runner = DiscoverRunner(verbosity=1)
        except ImportError:
            # Django <= 1.5
            from django.test.simple import DjangoTestSuiteRunner
            test_runner = DjangoTestSuiteRunner(verbosity=1)

        if django.VERSION >= (1, 7):
            django.setup()

        failures = test_runner.run_tests(self.apps)
        if failures:
            sys.exit(failures)
Beispiel #34
0
def runtests():
    if hasattr(django, 'setup'):
        django.setup()
    return DjangoTestSuiteRunner(failfast=False).run_tests([
        'crispy_forms.TestBasicFunctionalityTags',
        'crispy_forms.TestFormHelper',
        'crispy_forms.TestBootstrapFormHelper',
        'crispy_forms.TestBootstrap3FormHelper',
        'crispy_forms.TestFormLayout',
        'crispy_forms.TestBootstrapFormLayout',
        'crispy_forms.TestBootstrap3FormLayout',
        'crispy_forms.TestLayoutObjects',
        'crispy_forms.TestBootstrapLayoutObjects',
        'crispy_forms.TestDynamicLayouts',
    ],
                                                           verbosity=1,
                                                           interactive=True)
    def _new_tests(self):
        """
        Fire up the Django test suite developed for version 1.2
        """
        INSTALLED_APPS, settings_test = self.custom_settings()

        test_db = os.environ.get('DB', 'sqlite')
        if test_db == 'mysql':
            database = {
                'ENGINE': 'django.db.backends.mysql',
                'NAME': 'django',
                'USER': '******',
            }
        elif test_db == 'postgres':
            database = {
                'ENGINE': 'django.db.backends.postgresql_psycopg2',
                'USER': '******',
                'NAME': 'django',
                'OPTIONS': {
                    'autocommit': True,
                }
            }
        else:
            database = {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': os.path.join(self.DIRNAME, 'database.db'),
                'USER': '',
                'PASSWORD': '',
                'HOST': '',
                'PORT': '',
            }

        settings.configure(
            DEBUG = True,
            DATABASES = {
                'default': database,
            },
            INSTALLED_APPS = self.INSTALLED_APPS + INSTALLED_APPS + self.apps,
            **settings_test
        )

        from django.test.simple import DjangoTestSuiteRunner
        failures = DjangoTestSuiteRunner().run_tests(self.apps, verbosity=1)
        if failures:
            sys.exit(failures)
Beispiel #36
0
    def run_tests(self, test_labels=('pages', ), extra_tests=None):

        if coverage:
            cov = coverage()
            cov.erase()
            cov.use_cache(0)
            cov.start()

        results = DjangoTestSuiteRunner.run_tests(self, test_labels,
                                                  extra_tests)

        if coverage:
            cov.stop()
            app = get_app('pages')
            modules = get_all_coverage_modules(app)
            cov.html_report(modules, directory='coverage')

        sys.exit(results)
Beispiel #37
0
def runtests(*test_args):
    if not settings.configured:
        settings.configure(**DEFAULT_SETTINGS)

    # Compatibility with Django 1.7's stricter initialization
    if hasattr(django, "setup"):
        django.setup()

    if not test_args:
        test_args = ["tests"]

    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)

    from django.test.simple import DjangoTestSuiteRunner
    failures = DjangoTestSuiteRunner(
        verbosity=1, interactive=True, failfast=False).run_tests(test_args)
    sys.exit(failures)
 def _new_tests(self):
     settings.configure(
         DEBUG = True,
         DATABASES = {
             'default' : {
                 'ENGINE' : 'django.db.backends.sqlite3',
                 'NAME' : os.path.join(self.DIRNAME, 'database.db'),
                 'USER' : '',
                 'PASSWORD' : '',
                 'HOST' : '',
                 'PORT' : '',
             }
         },
         INSTALLED_APPS = self.INSTALLED_APPS + self.apps
     )
     from django.test.simple import DjangoTestSuiteRunner
     failures = DjangoTestSuiteRunner().run_tests(self.apps, verbosity=1)
     if failures:
         sys.exit(failures)
Beispiel #39
0
 def test_ticket_16885(self):
     """Features are also confirmed on mirrored databases."""
     old_db_connections = db.connections
     try:
         db.connections = db.ConnectionHandler({
             'default': {
                 'ENGINE': 'django.db.backends.sqlite3',
             },
             'slave': {
                 'ENGINE': 'django.db.backends.sqlite3',
                 'TEST_MIRROR': 'default',
             },
         })
         slave = db.connections['slave']
         self.assertEqual(slave.features.supports_transactions, None)
         DjangoTestSuiteRunner(verbosity=0).setup_databases()
         self.assertNotEqual(slave.features.supports_transactions, None)
     finally:
         db.connections = old_db_connections
Beispiel #40
0
 def run_tests(self):
     """
     Fire up the Django test suite developed for version 1.2
     """
     settings.configure(
         DEBUG=True,
         DATABASES={
             'default': {
                 'ENGINE': 'django.db.backends.sqlite3',
                 'NAME': os.path.join(self.DIRNAME, 'database.db'),
                 'USER': '',
                 'PASSWORD': '',
                 'HOST': '',
                 'PORT': '',
             }
         },
         LOGGING={
             'version': 1,
             'formatters': {
                 'simple': {
                     'format':
                     '%(levelname)s %(asctime)s %(name)s %(message)s'
                 }
             },
             'handlers': {
                 'console': {
                     'class': 'logging.StreamHandler',
                     'formatter': 'simple'
                 }
             },
             'loggers': {
                 'screamshot': {
                     'handlers': ['console'],
                     'level': 'DEBUG'
                 }
             }
         },
         INSTALLED_APPS=self.INSTALLED_APPS + self.apps)
     from django.test.simple import DjangoTestSuiteRunner
     failures = DjangoTestSuiteRunner().run_tests(self.apps, verbosity=1)
     if failures:  # pragma: no cover
         sys.exit(failures)
Beispiel #41
0
def runtests(*test_args):
    if not test_args:
        test_args = ['django_pandas']

    parent = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, parent)

    if django.VERSION < (1, 8):
        from django.test.simple import DjangoTestSuiteRunner
        failures = DjangoTestSuiteRunner(verbosity=1,
                                         interactive=True,
                                         failfast=False).run_tests(['tests'])
        sys.exit(failures)

    else:
        from django.test.runner import DiscoverRunner
        failures = DiscoverRunner(verbosity=1,
                                  interactive=True,
                                  failfast=False).run_tests(test_args)
        sys.exit(failures)
 def _new_tests(self):
     """
     Fire up the Django test suite developed for version 1.2
     """
     settings.configure(DEBUG=True,
                        DATABASES={
                            'default': {
                                'ENGINE': 'django.db.backends.sqlite3',
                                'NAME': 'foobar',
                                'USER': '',
                                'PASSWORD': '',
                                'HOST': '',
                                'PORT': '',
                            }
                        },
                        INSTALLED_APPS=self.INSTALLED_APPS + self.apps)
     from django.test.simple import DjangoTestSuiteRunner
     failures = DjangoTestSuiteRunner().run_tests(self.apps, verbosity=1)
     if failures:
         sys.exit(failures)
Beispiel #43
0
 def _tests_1_7(self):
     """
     Fire up the Django test suite developed for version 1.7 and up
     """
     test_settings = self.custom_settings
     installed_apps = test_settings.pop('INSTALLED_APPS', ())
     settings.configure(
         DEBUG=True,
         DATABASES=self.get_database(1.7),
         MIDDLEWARE_CLASSES=('django.middleware.common.CommonMiddleware',
                             'django.middleware.csrf.CsrfViewMiddleware'),
         INSTALLED_APPS=tuple(self.INSTALLED_APPS + installed_apps +
                              self.apps),
         **test_settings)
     from django.test.simple import DjangoTestSuiteRunner
     import django
     django.setup()
     failures = DjangoTestSuiteRunner().run_tests(self.apps, verbosity=1)
     if failures:
         sys.exit(failures)
Beispiel #44
0
    def _tests_1_7(self):
        """
        Fire up the Django test suite developed for version 1.7 and up
        """
        INSTALLED_APPS, settings_test = self.get_custom_settings()

        settings.configure(
            DEBUG=True,
            DATABASES=self.get_database(),
            MIDDLEWARE_CLASSES=('django.middleware.common.CommonMiddleware',
                                'django.middleware.csrf.CsrfViewMiddleware'),
            INSTALLED_APPS=self.INSTALLED_APPS + INSTALLED_APPS + self.apps,
            **settings_test)

        from django.test.simple import DjangoTestSuiteRunner
        import django
        django.setup()
        failures = DjangoTestSuiteRunner().run_tests(self.apps, verbosity=1)
        if failures:
            sys.exit(failures)
Beispiel #45
0
def runtests(*test_args):
    from django.test.simple import DjangoTestSuiteRunner

    if 'south' in settings.INSTALLED_APPS:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    if not test_args:  ## setup.py test
        test_args = ['ajaxutils_tests', '--jenkins']
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    if '--jenkins' in test_args:
        call_command('jenkins',
                     'ajaxutils_tests',
                     verbosity=1,
                     interactive=True)
        sys.exit(0)
    else:
        failures = DjangoTestSuiteRunner().run_tests(test_args)
        sys.exit(failures)
Beispiel #46
0
    def run_tests(self, test_labels=('pages', ), extra_tests=None):

        if coverage_module_present:
            cov = coverage()
            cov.erase()
            cov.use_cache(0)
            cov.start()
        else:
            print("No coverage support")

        results = DjangoTestSuiteRunner.run_tests(self, test_labels,
                                                  extra_tests)

        if coverage_module_present:
            cov.stop()
            app = get_app('pages')
            modules = get_all_coverage_modules(app)
            cov.html_report(modules, directory='coverage')
            print('Coverage report stored in directory "coverage"')

        sys.exit(results)
Beispiel #47
0
 def run_tests(self):
     """
     Fire up the Django test suite developed for version 1.2
     """
     settings.configure(
         DATABASES={
             'default': {
                 'ENGINE': 'django.contrib.gis.db.backends.spatialite',
                 'NAME': os.path.join(self.DIRNAME, 'database.db'),
                 'USER': '',
                 'PASSWORD': '',
                 'HOST': '',
                 'PORT': '',
             }
         },
         INSTALLED_APPS=self.INSTALLED_APPS + self.apps,
     )
     from django.test.simple import DjangoTestSuiteRunner
     failures = DjangoTestSuiteRunner().run_tests(self.apps, verbosity=1)
     if failures:  # pragma: no cover
         sys.exit(failures)
Beispiel #48
0
def before_all(context):
    from django.test.simple import DjangoTestSuiteRunner
    # We'll use thise later to frog-march Django through the motions
    # of setting up and tearing down the test environment, including
    # test databases.
    context.runner = DjangoTestSuiteRunner()

    patch_for_test_db_setup()

    host = context.host = 'localhost'
    port = context.port = getattr(settings, 'TESTING_MECHANIZE_INTERCEPT_PORT',
                                  17681)
    # NOTE: Nothing is actually listening on this port. wsgi_intercept
    # monkeypatches the networking internals to use a fake socket when
    # connecting to this port.
    wsgi_intercept.add_wsgi_intercept(host, port, WSGIHandler)

    def browser_url(url):
        """Create a URL for the virtual WSGI server.
        e.g context.browser_url('/'), context.browser_url(reverse('my_view'))
        """
        return urlparse.urljoin('http://%s:%d/' % (host, port), url)

    context.browser_url = browser_url

    def parse_soup():
        r = context.browser.response()
        h = r.read()
        r.seek(0)
        return BeautifulSoup(h)

    context.parse_soup = parse_soup

    def parse_lxml():
        r = context.browser.response()
        data = r.read()
        r.seek(0)
        return html.fromstring(data)

    context.parse_lxml = parse_lxml
Beispiel #49
0
 def run_tests(self):
     """
     Fire up the Django test suite developed for version 1.2
     """
     settings.configure(
         TEMPLATE_DIRS = ('jsignature/templates/',),
         ROOT_URLCONF = 'jsignature.tests',
         DEBUG = True,
         DATABASES = {
             'default': {
                 'ENGINE': 'django.db.backends.sqlite3',
                 'NAME': os.path.join(self.DIRNAME, 'database.db'),
                 'USER': '',
                 'PASSWORD': '',
                 'HOST': '',
                 'PORT': '',
             }
         },
         MIDDLEWARE_CLASSES = (
             'django.contrib.sessions.middleware.SessionMiddleware',
             'django.middleware.common.CommonMiddleware',
             'django.middleware.csrf.CsrfViewMiddleware',
             'django.contrib.auth.middleware.AuthenticationMiddleware',
             'django.contrib.messages.middleware.MessageMiddleware',
         ),
         INSTALLED_APPS = self.INSTALLED_APPS + self.apps
     )
     # Setup is needed for Django >= 1.7
     import django
     if hasattr(django, 'setup'):
         django.setup()
     try:
         from django.test.runner import DiscoverRunner
         failures = DiscoverRunner().run_tests(self.apps, verbosity=1)
     except ImportError:
         # DjangoTestSuiteRunner has been deprecated in Django 1.7
         from django.test.simple import DjangoTestSuiteRunner
         failures = DjangoTestSuiteRunner().run_tests(self.apps, verbosity=1)
     if failures: # pragma: no cover
         sys.exit(failures)
Beispiel #50
0
 def _new_tests(self):
     """
     Fire up the Django test suite developed for version 1.2
     """
     settings.configure(
         DEBUG=True,
         DATABASES={
             'default': {
                 'ENGINE': 'django.db.backends.sqlite3',
                 'NAME': os.path.join(self.DIRNAME, 'database.db'),
                 'USER': '',
                 'PASSWORD': '',
                 'HOST': '',
                 'PORT': '',
             }
         },
         INSTALLED_APPS=self.INSTALLED_APPS + self.apps,
         ROOT_URLCONF='unfriendly.tests.urls',
     )
     from django.test.simple import DjangoTestSuiteRunner
     failures = DjangoTestSuiteRunner().run_tests(self.apps, verbosity=1)
     if failures:
         sys.exit(failures)
Beispiel #51
0
 def test_transaction_support(self):
     """Ticket #16329: sqlite3 in-memory test databases"""
     old_db_connections = db.connections
     for option in ('NAME', 'TEST_NAME'):
         try:
             db.connections = db.ConnectionHandler({
                 'default': {
                     'ENGINE': 'django.db.backends.sqlite3',
                     option: ':memory:',
                 },
                 'other': {
                     'ENGINE': 'django.db.backends.sqlite3',
                     option: ':memory:',
                 },
             })
             other = db.connections['other']
             DjangoTestSuiteRunner(verbosity=0).setup_databases()
             msg = "DATABASES setting '%s' option set to sqlite3's ':memory:' value shouldn't interfere with transaction support detection." % option
             # Transaction support should be properly initialised for the 'other' DB
             self.assertTrue(other.features.supports_transactions, msg)
             # And all the DBs should report that they support transactions
             self.assertTrue(connections_support_transactions(), msg)
         finally:
             db.connections = old_db_connections
Beispiel #52
0
 def _new_tests(self):
     """
     Fire up the Django test suite developed for version 1.2
     """
     settings.configure(
         DEBUG=True,
         DATABASES={
             'default': {
                 'ENGINE': 'django.db.backends.sqlite3',
                 'NAME': os.path.join(self.DIRNAME, 'database.db'),
                 'USER': '',
                 'PASSWORD': '',
                 'HOST': '',
                 'PORT': '',
             }
         },
         INSTALLED_APPS=self.INSTALLED_APPS + self.apps,
         FACEBOOK_REALTIME_VERIFY_TOKEN=
         'EJEgWVcZCyx7NNoKT83xbxrKPy0sQPYZBZCkEZAm31PPoOoHojlTHPhGgZDAA',
         ROOT_URLCONF='urlstest')
     from django.test.simple import DjangoTestSuiteRunner
     failures = DjangoTestSuiteRunner().run_tests(self.apps, verbosity=1)
     if failures:
         sys.exit(failures)
Beispiel #53
0
 def tearDownClass(cls):
     DjangoTestSuiteRunner().teardown_databases(cls.old_state)
Beispiel #54
0
settings.configure(
    DEBUG=True,
    #    AUTH_USER_MODEL='testdata.CustomUser',
    DATABASES={'default': {
        'ENGINE': 'django.db.backends.sqlite3',
    }},
    SITE_ID=1,
    ROOT_URLCONF=None,
    INSTALLED_APPS=(
        'djmoney',
        'djmoney.tests.testapp',
        'south',
    ),
    USE_TZ=True,
    SOUTH_TESTS_MIGRATE=True,
)

from django.test.simple import DjangoTestSuiteRunner
test_runner = DjangoTestSuiteRunner(verbosity=1)

# If you use South for migrations, uncomment this to monkeypatch
# syncdb to get migrations to run.
from south.management.commands import patch_for_test_db_setup
patch_for_test_db_setup()

failures = test_runner.run_tests([
    'djmoney',
])
if failures:
    sys.exit(failures)
Beispiel #55
0
 def setUpClass(cls):
     cls.old_state = DjangoTestSuiteRunner().setup_databases()
Beispiel #56
0
def run_tests(test_labels, verbosity=1, interactive=True, failfast=False, extra_tests=[]):
    """
    Run the unit tests for all the test labels in the provided list.
    Labels must be of the form:
     - app.TestClass.test_method
        Run a single specific test method
     - app.TestClass
        Run all the test methods in a given class
     - app
        Search for doctests and unittests in the named application.

    When looking for tests, the test runner will look in the models and
    tests modules for the application.

    A list of 'extra' tests may also be provided; these tests
    will be added to the test suite.

    If the settings file has an entry for COVERAGE_MODULES or test_labels is true it will prints the
    coverage report for modules/apps

    Returns number of tests that failed.
    """

    do_coverage = (hasattr(settings, 'COVERAGE_MODULES') or
                   hasattr(settings, 'COVERAGE_APPS') or
                   bool(test_labels))
    if do_coverage:
        coverage.erase()
        coverage.start()
    
    DjangoTestSuiteRunner = None
    try:
        from django.test.simple import DjangoTestSuiteRunner
    except ImportError:
        from django.test import simple
    
    if DjangoTestSuiteRunner:
        testrunner = DjangoTestSuiteRunner(verbosity=verbosity, interactive=interactive, failfast=failfast)
        retval = testrunner.run_tests(test_labels, extra_tests)
    else:
        retval = simple.run_tests(test_labels, verbosity, interactive, extra_tests)

    if do_coverage:
        coverage.stop()

        # Print code metrics header
        print ''
        print '----------------------------------------------------------------------'
        print ' Unit Test Code Coverage Results'
        print '----------------------------------------------------------------------'

        # try to import all modules for the coverage report.
        modules = []
        if test_labels or hasattr(settings, 'COVERAGE_APPS'):
            # apps entered at the command line prompt override those specified in settings
            labels = test_labels or settings.COVERAGE_APPS
            for label in labels:
                label = label.split('.')[0] #remove test class or test method from label
                pkg = _get_app_package(label)
                modules.extend(_package_modules(*pkg))
        elif hasattr(settings, 'COVERAGE_MODULES'):
            modules = [__import__(module, {}, {}, ['']) for module in settings.COVERAGE_MODULES]

        if hasattr(settings, 'COVERAGE_EXCLUDE_MODULES'):
            for exclude_module_name in settings.COVERAGE_EXCLUDE_MODULES:
                # Test designed to avoid accidentally removing a module whose
                # name is prefixed by an excluded module name, but still remove
                # submodules
                modules = [module for module in modules
                    if not module.__name__ == exclude_module_name and
                    not module.__name__.startswith(exclude_module_name + '.')]

        coverage.report(modules, show_missing=1)

    return retval
Beispiel #57
0
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(DIRNAME, 'database.db'),
    }
}

settings.configure(
    DEBUG=True,
    DATABASES=DATABASES,
    USE_TZ=True,
    AUTHY_KEY='12345678910111213141516171819201234567891011121314151617181920',
    ROOT_URLCONF='authy.urls',
    PASSWORD_HASHERS=('django.contrib.auth.hashers.MD5PasswordHasher',
                      ),  # simple fast hasher but not secure
    INSTALLED_APPS=(
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.admin',
        'authy',
    ))

from django.test.simple import DjangoTestSuiteRunner

call_command('syncdb', interactive=False)

failures = DjangoTestSuiteRunner().run_tests([
    'authy',
], verbosity=1)
if failures:
    sys.exit(failures)
Beispiel #58
0
 def __init__(self, on_run_suite):
     DjangoTestSuiteRunner.__init__(self)
     self.on_run_suite = on_run_suite
Beispiel #59
0
def runtests():
    test_runner = DjangoTestSuiteRunner(verbosity=1)
    failures = test_runner.run_tests([
        APP,
    ])
    sys.exit(failures)
Beispiel #60
0
 def run_tests(test_args, verbosity, interactive):
     runner = DjangoTestSuiteRunner(
         verbosity=verbosity, interactive=interactive, failfast=False)
     return runner.run_tests(test_args)