Esempio n. 1
0
    def __init__(self, *args, **kwargs):
        self.configure()
        self.cov = coverage()
        self.cov.start()
        self.packages = self.resolve_packages()

        parser = argparse.ArgumentParser()
        parser.add_argument('-a', '--autoreload', dest='autoreload',
                action='store_const', const=True, default=False,)
        parser.add_argument('-f', '--failfast', dest='failfast',
                action='store_const', const=True, default=False,)
        parser.add_argument('-l', '--label', dest='label')
        self.options = vars(parser.parse_args(sys.argv[2:]))
        sys.argv = sys.argv[:2]

        super(SetupTestSuite, self).__init__(tests=self.build_tests(),
                *args, **kwargs)

        # Setup testrunner.
        from django.test.simple import DjangoTestSuiteRunner
        self.test_runner = DjangoTestSuiteRunner(
            verbosity=1,
            interactive=True,
            failfast=False
        )
        # South patches the test management command to handle the
        # SOUTH_TESTS_MIGRATE setting. Apply that patch if South is installed.
        try:
            from south.management.commands import patch_for_test_db_setup
            patch_for_test_db_setup()
        except ImportError:
            pass
        self.test_runner.setup_test_environment()
        self.old_config = self.test_runner.setup_databases()
def main():
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=2, failfast=False)

    if len(sys.argv) > 1:
        test_modules = sys.argv[1:]
    elif len(sys.argv) == 1:
        test_modules = []
    else:
        print(usage())
        sys.exit(1)

    if django.VERSION >= (1, 6, 0):
        # this is a compat hack because in django>=1.6.0 you must provide
        # module like "userena.contrib.umessages" not "umessages"
        test_modules = [
            get_app(module_name).__name__[:-7] for module_name in test_modules
        ]

    if django.VERSION < (1, 7, 0):
        # starting from 1.7.0 built in django migrations are run
        # for older releases this patch is required to enable testing with
        # migrations
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    failures = test_runner.run_tests(test_modules or ['userena'])
    sys.exit(failures)
Esempio n. 3
0
	def handle(self, *fixture_labels, **options):
		from django.core.management import call_command
		from django.db import connection
		from south.management.commands import patch_for_test_db_setup

		patch_for_test_db_setup()

		verbosity = int(options.get('verbosity'))
		interactive = options.get('interactive')
		addrport = options.get('addrport')

		# Create a test database.
		db_name = connection.creation.create_test_db(verbosity=verbosity, autoclobber=not interactive)

		# Import the fixture data into the test database.
		call_command('loaddata', *fixture_labels, **{'verbosity': verbosity})

		# Run the development server. Turn off auto-reloading because it causes
		# a strange error -- it causes this handle() method to be called
		# multiple times.
		shutdown_message = '\nServer stopped.\nNote that the test database, %r, has not been deleted. You can explore it on your own.' % db_name
		use_threading = connection.features.test_db_allows_multiple_connections
		call_command('runserver',
			addrport=addrport,
			shutdown_message=shutdown_message,
			use_reloader=False,
			use_ipv6=options['use_ipv6'],
			use_threading=use_threading
		)
Esempio n. 4
0
def runtests():
    from south.management.commands import patch_for_test_db_setup
    patch_for_test_db_setup()
    test_runner = get_runner(settings)
    test_runner = test_runner(interactive=True, verbosity=1, failfast=False)
    failures = test_runner.run_tests([])
    sys.exit(bool(failures))
Esempio n. 5
0
def django_tests(verbosity, interactive, failfast, test_labels):
    import django
    from django.conf import settings

    if hasattr(django, 'setup'):
        # Django >= 1.7 requires this for setting up the application.
        django.setup()

    if django.VERSION < (1, 7):
        # must be imported after settings are set up
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    from django.test.utils import get_runner
    TestRunner = get_runner(settings)

    if not test_labels:
        # apps to test
        test_labels = CORE_TEST_MODULES + get_contrib_test_modules()

    test_runner = TestRunner(verbosity=verbosity, interactive=interactive,
                             failfast=failfast)
    failures = test_runner.run_tests(test_labels)

    teardown()
    return failures
Esempio n. 6
0
    def __enter__(self):
        try:
            patch_for_test_db_setup()
        except NameError:
            pass

        connection.creation.create_test_db(self.verbosity)
Esempio n. 7
0
    def handle(self, *test_labels, **options):
        from django.conf import settings
        from django.test.utils import get_runner
        patch_for_test_db_setup()
        
        test_labels = ('locations', 'parsed_xforms', \
                    'nga_districts', 'phone_manager', 'surveyor_manager', \
                    'xform_manager', 'map_xforms', 'submission_qr',)
        
        verbosity = int(options.get('verbosity', 1))
        interactive = options.get('interactive', True)
        failfast = options.get('failfast', False)
        TestRunner = get_runner(settings)
        
        if hasattr(TestRunner, 'func_name'):
            # Pre 1.2 test runners were merely functions,
            # and did not support the 'failfast' option.
            import warnings
            warnings.warn(
                'Function-based test runners are deprecated. Test runners should be classes with a run_tests() method.',
                PendingDeprecationWarning
            )
            failures = TestRunner(test_labels, verbosity=verbosity, interactive=interactive)
        else:
            test_runner = TestRunner(verbosity=verbosity, interactive=interactive, failfast=failfast)
            failures = test_runner.run_tests(test_labels)

        if failures:
            sys.exit(bool(failures))
Esempio n. 8
0
 def setup_databases(self):
     if 'south' in settings.INSTALLED_APPS:
         from south.management.commands import (
             patch_for_test_db_setup  # pylint: disable=F0401
         )
         patch_for_test_db_setup()
     return super(CITestSuiteRunner, self).setup_databases()
Esempio n. 9
0
 def south_patch(self):
     try:
         from south.management.commands import patch_for_test_db_setup
     except ImportError:
         pass
     else:
         patch_for_test_db_setup()
Esempio n. 10
0
def switch_to_test_database():
    """
    Switching to the test database
    """
    logging.info("Setting up a test database ...\n")

    try:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()
    except ImportError:
        pass

    world.test_runner = DjangoTestSuiteRunner(interactive=False)
    world.test_runner.setup_test_environment()
    world.test_db = world.test_runner.setup_databases()
    call_command('syncdb', **{
        'settings': settings.SETTINGS_MODULE,
        'interactive': False,
        'verbosity': 0
    })

    # Reload mongodb database
    settings.MONGODB_DATABASE = settings.MONGODB_TEST_DATABASE
    for model in [Document, Entry, Notification]:
        model.objects.load()
        model.objects.collection.remove()
Esempio n. 11
0
def _handle_south():
    from django.conf import settings
    if 'south' in settings.INSTALLED_APPS:
        # Handle south.
        from django.core import management

        try:
            # if `south` >= 0.7.1 we can use the test helper
            from south.management.commands import patch_for_test_db_setup
        except ImportError:
            # if `south` < 0.7.1 make sure it's migrations are disabled
            management.get_commands()
            management._commands['syncdb'] = 'django.core'
        else:
            # Monkey-patch south.hacks.django_1_0.SkipFlushCommand to load
            # initial data.
            # Ref: http://south.aeracode.org/ticket/1395#comment:3
            import south.hacks.django_1_0
            from django.core.management.commands.flush import (
                Command as FlushCommand)

            class SkipFlushCommand(FlushCommand):
                def handle_noargs(self, **options):
                    # Reinstall the initial_data fixture.
                    from django.core.management import call_command
                    # `load_initial_data` got introduces with Django 1.5.
                    load_initial_data = options.get('load_initial_data', None)
                    if load_initial_data or load_initial_data is None:
                        # Reinstall the initial_data fixture.
                        call_command('loaddata', 'initial_data', **options)
                    # no-op to avoid calling flush
                    return
            south.hacks.django_1_0.SkipFlushCommand = SkipFlushCommand

            patch_for_test_db_setup()
Esempio n. 12
0
 def handle(self, *args, **options):
     
     # Replace the DB name with test DB name in main settings
     # since this is what destroy_test_db looks for to determine
     # the name of the test_db.
     for alias in connections:
         connection = connections[alias]
         original_name = connection.settings_dict['NAME']
         if connection.settings_dict['TEST_NAME']:
             test_database_name = connection.settings_dict['TEST_NAME']
         else:
             test_database_name = TEST_DATABASE_PREFIX + connection.settings_dict['NAME']
         connection.settings_dict['NAME'] = test_database_name
         
         # try to delete db if it already exists, so we can recreate.
         try:
             connection.creation.destroy_test_db(original_name)
         except Exception, e:
             pass
         
         # check if we have south installed, and so overide syncdb so 
         # we also run migrations. Uses same method as south's test 
         # command override.
         try:
             from south.management.commands import patch_for_test_db_setup
         except ImportError:
             patch_for_test_db_setup = lambda: None
         
         patch_for_test_db_setup()
         connection.creation.create_test_db()
Esempio n. 13
0
   def handle(self, *test_labels, **options):
      """Trigger both south and selenium tests."""

      run_south_tests = bool(options.get('run_normal_tests', False))
      run_selenium_tests = bool(options.get('run_selenium_tests', False))

      # Check test types
      if (run_south_tests and run_selenium_tests or
         not run_south_tests and not run_selenium_tests):
         logger.error("You must specify exactly one of --selenium-tests and --normal-tests.")
         sys.exit(1)

      # Apply the south patch for syncdb, migrate commands during tests
      patch_for_test_db_setup()

      if run_south_tests:
         test_south.Command.handle(self, *test_labels, **options)
      elif run_selenium_tests:
         # We don't want to call any super handle function, because it will
         # try to run tests in addition to parsing command line options.
         # Instead, we parse the relevant options ourselves.
         verbosity = int(options.get('verbosity', 1))
         interactive = options.get('interactive', True)
         failfast = options.get('failfast', False)

         test_runner = SeleniumTestRunner(verbosity=verbosity, interactive=interactive, failfast=failfast)
         test_runner.selenium = True
         test_runner.selenium_only = True
         failures = test_runner.run_tests(test_labels)
         if failures:
            sys.exit(bool(failures))
Esempio n. 14
0
    def setup_databases(self, verbosity, autoclobber, **kwargs):
        # Taken from Django 1.2 code, (C) respective Django authors. Modified for backward compatibility by me
        connections = self._get_databases()
        old_names = []
        mirrors = []

        from django.conf import settings
        if 'south' in settings.INSTALLED_APPS:
            from south.management.commands import patch_for_test_db_setup

            settings.SOUTH_TESTS_MIGRATE = getattr(settings, 'DST_RUN_SOUTH_MIGRATIONS', True)
            patch_for_test_db_setup()

        for alias in connections:
            connection = connections[alias]
            # If the database is a test mirror, redirect it's connection
            # instead of creating a test database.
            if 'TEST_MIRROR' in connection.settings_dict and connection.settings_dict['TEST_MIRROR']:
                mirrors.append((alias, connection))
                mirror_alias = connection.settings_dict['TEST_MIRROR']
                connections._connections[alias] = connections[mirror_alias]
            else:
                if 'NAME' in connection.settings_dict:
                    old_names.append((connection, connection.settings_dict['NAME']))
                else:
                    old_names.append((connection, connection.settings_dict['DATABASE_NAME']))
                connection.creation.create_test_db(verbosity=verbosity, autoclobber=autoclobber)
        return old_names, mirrors
Esempio n. 15
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)
Esempio n. 16
0
    def setUp(self):
        # Set up the django test framework.
        os.environ['DJANGO_SETTINGS_MODULE'] = 'website.settings'
        from django.conf import settings
        from django.test.utils import setup_test_environment
        from django.db import connection
        from south.management.commands import patch_for_test_db_setup

        # If DEBUG = True, django will sometimes take different code paths.
        settings.DEBUG = False

        self.django_db = settings.DATABASE_NAME
        setup_test_environment()
        patch_for_test_db_setup()
        connection.creation.create_test_db(verbosity=0)

        # A fake cardstories service just to benefit from settings directories.
        class FakeService:
            def __init__(self, settings):
                self.settings = settings

        # Instantiate our test subject.
        self.auth = djangoauth.Plugin(FakeService({'plugins-libdir': '.',
                                                   'plugins-confdir': '../fixture'}), [])

        # Use the fake client in the plugin instead of twisted's getPage.
        self.auth.getPage = FakeTwistedWebClient().getPage
def runtests(verbosity=1, interactive=False, failfast=False, *test_args):
    if 'south' in settings.INSTALLED_APPS:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()


    test_runner = UnaccentDjangoTestSuiteRunner(verbosity=verbosity, interactive=interactive, failfast=failfast)
    return test_runner.run_tests(test_labels=None, extra_tests=None)
Esempio n. 18
0
def main():
    if 'south' in settings.INSTALLED_APPS:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    test_runner = get_runner(settings)(interactive=False, verbosity=2)
    failures = test_runner.run_tests(['peavy'])
    sys.exit(failures)
Esempio n. 19
0
def main():
    from django.test.utils import get_runner
    from south.management.commands import patch_for_test_db_setup

    patch_for_test_db_setup()
    test_runner = get_runner(settings)(interactive=False)
    failures = test_runner.run_tests([app.split('.')[-1] for app in TEST_APPS])
    sys.exit(failures)
Esempio n. 20
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()
Esempio n. 21
0
def main():
    TestRunner = get_runner(settings)

    # Ugly parameter parsing. We probably want to improve that in future
    # or just use default django test command. This may be problematic,
    # knowing how testing in Django changes from version to version.
    if '-p' in sys.argv:
        try:
            pos = sys.argv.index('-p')
            pattern = sys.argv.pop(pos) and sys.argv.pop(pos)
        except IndexError:
            print(usage())
            sys.exit(1)
    else:
        pattern = None

    test_modules = sys.argv[1:]

    test_runner = TestRunner(verbosity=2, failfast=False, pattern=pattern)

    if len(sys.argv) > 1:
        test_modules = sys.argv[1:]
    elif len(sys.argv) == 1:
        test_modules = []
    else:
        print(usage())
        sys.exit(1)

    if  (1, 6, 0) <= django.VERSION < (1, 9, 0):
        # this is a compat hack because in django>=1.6.0 you must provide
        # module like "userena.contrib.umessages" not "umessages"
        from django.db.models import get_app
        test_modules = [
            # be more strict by adding .tests to not run umessages tests twice
            # if both userena and umessages are tested
            get_app(module_name).__name__[:-7] + ".tests"
            for module_name
            in test_modules
        ]
    elif django.VERSION >= (1, 9, 0):
        from django.apps import apps
        test_modules = [
            # be more strict by adding .tests to not run umessages tests twice
            # if both userena and umessages are tested
            apps.get_app_config(module_name).name + ".tests"
            for module_name
            in test_modules
        ]

    if django.VERSION < (1, 7, 0):
        # starting from 1.7.0 built in django migrations are run
        # for older releases this patch is required to enable testing with
        # migrations
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    failures = test_runner.run_tests(test_modules or ['userena'])
    sys.exit(failures)
Esempio n. 22
0
def runtests():
    if 'south' in settings.INSTALLED_APPS:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=1, interactive=True)
    failures = test_runner.run_tests(['tester'])
    sys.exit(bool(failures))
Esempio n. 23
0
def runtests(*test_args, **kwargs):
    if 'south' in settings.INSTALLED_APPS:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    test_runner = NoseTestSuiteRunner(**kwargs)

    failures = test_runner.run_tests(test_args)
    sys.exit(failures)
Esempio n. 24
0
def runtests():
    patch_for_test_db_setup()
    apps = sys.argv[1:] or ['allaccess', ]
    if SWAPPED and VERSION[0] == 1 and VERSION[1] < 6:
        apps.append('custom')
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
    failures = test_runner.run_tests(apps)
    sys.exit(failures)
Esempio n. 25
0
 def __init__(self, *test_args, **kwargs):
     super(TestsWrapper, self).__init__()
     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:
         test_args = ['cmsroles.tests']
         kwargs.setdefault('interactive', False)
         test_runner = NoseTestSuiteRunner(**kwargs)
         self._failures = test_runner.run_tests(test_args)
Esempio n. 26
0
def _handle_south_management_command():
    try:
        # if `south` >= 0.7.1 we can use the test helper
        from south.management.commands import patch_for_test_db_setup
    except ImportError:
        # if `south` < 0.7.1 make sure it's migrations are disabled
        management.get_commands()
        management._commands['syncdb'] = 'django.core'
    else:
        patch_for_test_db_setup()
Esempio n. 27
0
def patch_settings(options):
    """
    Patch Django settings/environment.
    """
    if 'south' in settings.INSTALLED_APPS:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    if options.get('liveserver') is not None:
        os.environ['DJANGO_LIVE_TEST_SERVER_ADDRESS'] = options['liveserver']
Esempio n. 28
0
def runtests(*test_args, **kwargs):
    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:
        test_args = ['attachments']

    failures = run_tests(test_args, verbosity=kwargs.get('verbosity', 1), interactive=kwargs.get('interactive', False), failfast=kwargs.get('failfast'))
    sys.exit(failures)
Esempio n. 29
0
 def setup():
     setup_test_environment()
     if not hasattr(settings, 'DEBUG'):
         settings.DEBUG = False
     if 'south' in settings.INSTALLED_APPS:
         from south.management.commands import patch_for_test_db_setup
         patch_for_test_db_setup()
     from django.db import connection
     connection.creation.create_test_db(1, True)
     return Client()
Esempio n. 30
0
def runtests(*test_args):
    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:
        test_args = ['sentry']
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    failures = run_tests(test_args, verbosity=1, interactive=True)
    sys.exit(failures)
Esempio n. 31
0
def runtests(*test_args, **kwargs):
    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:
        test_args = ['tests']

    test_runner = NoseTestSuiteRunner(**kwargs)

    failures = test_runner.run_tests(test_args)
    sys.exit(failures)
Esempio n. 32
0
def runtests(verbosity, failfast, interactive, test_labels):

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

  test_runner = DjangoTestSuiteRunner(
      verbosity=verbosity,
      interactive=interactive,
      failfast=failfast)

  sys.exit(test_runner.run_tests(test_labels))
Esempio n. 33
0
def runtests(*test_args, **kwargs):
    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:
        test_args = ['tests']
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    test_runner = DjangoTestSuiteRunner(verbosity=kwargs.get('verbosity', 1), interactive=kwargs.get('interactive', False), failfast=kwargs.get('failfast'))
    failures = test_runner.run_tests(test_args)
    sys.exit(failures)
Esempio n. 34
0
    def handle(self, *args, **options):
        setup_test_environment()

        verbosity = int(options.get('verbosity', 3))
        no_color = int(options.get('no_color', False))
        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)
        test_database = options.get('test_database', False)
        smtp_queue = options.get('smtp_queue', False)
        tags = options.get('tags', None)
        failfast = options.get('failfast', False)
        auto_pdb = options.get('auto_pdb', False)
        threading = options.get('use_threading', True)
        with_summary = options.get('summary_display', False)

        if test_database:
            migrate_south = getattr(settings, "SOUTH_TESTS_MIGRATE", True)
            try:
                from south.management.commands import patch_for_test_db_setup
                patch_for_test_db_setup()
            except:
                migrate_south = False
                pass

            from django.test.utils import get_runner
            self._testrunner = get_runner(settings)(interactive=False)
            self._testrunner.setup_test_environment()
            self._old_db_config = self._testrunner.setup_databases()

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

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

        paths = self.get_paths(args, apps_to_run, apps_to_avoid)
        server = get_server(port=options['port'], threading=threading)

        if run_server:
            try:
                server.start()
            except LettuceServerException, e:
                raise SystemExit(e)
Esempio n. 35
0
def runtests():
    if hasattr(django, 'setup'):
        django.setup()
    patch_for_test_db_setup()
    apps = sys.argv[1:] or [
        'allaccess',
    ]
    if SWAPPED and VERSION[0] == 1 and VERSION[1] < 6:
        apps.append('custom')
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=1, interactive=True, failfast=False)
    failures = test_runner.run_tests(apps)
    sys.exit(failures)
Esempio n. 36
0
def runtests(*test_args, **kwargs):
    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:
        test_args = ['tests']

    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)
    test_runner = prepare_test_runner(**kwargs)
    failures = test_runner.run_tests(test_args)
    sys.exit(failures)
Esempio n. 37
0
def runtests(*test_args, **kwargs):
    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:
        test_args = ['contact_form']

    failures = run_tests(test_args,
                         verbosity=kwargs.get('verbosity', 1),
                         interactive=kwargs.get('interactive', False),
                         failfast=kwargs.get('failfast'))
    sys.exit(failures)
Esempio n. 38
0
def before_all(context):
    # Even though DJANGO_SETTINGS_MODULE is set, this may still be
    # necessary. Or it may be simple CYA insurance.
    from django.core.management import setup_environ
    from vsq import settings
    setup_environ(settings)

    ### Take a TestRunner hostage.
    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(verbosity=2)

    ## 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()

    ### Set up the WSGI intercept "port".
    import wsgi_intercept, urlparse
    from django.core.handlers.wsgi import WSGIHandler
    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

    ### BeautifulSoup is handy to have nearby. (Substitute lxml or html5lib as you see fit)
    from bs4 import BeautifulSoup

    def parse_soup():
        """Use BeautifulSoup to parse the current response and return the DOM tree.
        """
        r = context.browser.response()
        html = r.read()
        r.seek(0)
        return BeautifulSoup(html)

    context.parse_soup = parse_soup
Esempio n. 39
0
    def handle(self, *test_labels, **options):
        patch_for_test_db_setup()
        output_dir = options.get('output_dir')

        verbosity = int(options.get('verbosity', 1))
        interactive = options.get('interactive', True)

        test_runner = XmlDjangoTestSuiteRunner(output_dir=output_dir,
                                               interactive=interactive,
                                               verbosity=verbosity)
        failures = test_runner.run_tests(test_labels)

        if failures:
            sys.exit(bool(failures))
Esempio n. 40
0
def run_tests(*test_args):
    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:
        test_args = ['tests']

    # Run tests
    test_runner = NoseTestSuiteRunner(verbosity=1)
    num_failures = test_runner.run_tests(test_args)

    if num_failures > 0:
        sys.exit(num_failures)
def run_tests(*test_args, **kwargs):
    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:
        test_args = ['entity_emailer']

    kwargs.setdefault('interactive', False)

    test_runner = NoseTestSuiteRunner(**kwargs)

    failures = test_runner.run_tests(test_args)
    sys.exit(failures)
Esempio n. 42
0
def runtests(*test_args, **kwargs):
    if django.VERSION[:2] >= (1, 7):
        django.setup()
    if 'south' in settings.INSTALLED_APPS and south_installed:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    if not test_args:
        test_args = ['pybb']

    test_runner = Runner(verbosity=kwargs.get('verbosity', 1), interactive=kwargs.get('interactive', False),
                         failfast=kwargs.get('failfast'))
    failures = test_runner.run_tests(test_args)
    sys.exit(failures)
Esempio n. 43
0
    def handle(self, *test_labels, **options):
        patch_for_test_db_setup()

        from django.conf import settings
        from django.test.utils import get_runner

        verbosity = int(options.get('verbosity', 1))
        interactive = options.get('interactive', True)
        failfast = options.get('failfast', False)
        TestRunner = get_runner(settings)

        test_runner = TestRunner(verbosity=verbosity, interactive=interactive, failfast=failfast)
        failures = test_runner.run_tests(test_labels)

        sys.exit(bool(failures))
Esempio n. 44
0
    def handle(self, *test_labels, **options):
        # HACK: ensure Django configuratio is read in
        configure(**getattr(settings, 'MULE_CONFIG', {}))

        settings.TEST = True
        settings.DEBUG = False

        if 'south' in settings.INSTALLED_APPS:
            patch_for_test_db_setup()

        test_runner = DjangoTestSuiteRunner(**options)
        result = test_runner.run_tests(test_labels)

        if result:
            sys.exit(bool(result))
Esempio n. 45
0
def runtests(*test_args, **kwargs):
    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:
        test_args = ['celery_rpc']

    if sys.version_info >= (3, 10, 0):
        from django.test.runner import DiscoverRunner
        test_runner = DiscoverRunner(**kwargs)
    else:
        test_runner = NoseTestSuiteRunner(**kwargs)

    failures = test_runner.run_tests(test_args)
    sys.exit(failures)
Esempio n. 46
0
def runtests(*test_args):
    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:
        test_args = ['ticketing']
    parent = dirname(abspath(__file__))
    sys.path.insert(0, parent)

    from django.test.utils import get_runner
    TestRunner = get_runner(settings)

    test_runner = TestRunner(verbosity=0, interactive=True, failfast=True)
    failures = test_runner.run_tests(test_args)
    sys.exit(bool(failures))
Esempio n. 47
0
def main():
    TestRunner = get_runner(settings)
    test_runner = TestRunner(verbosity=2)

    if len(sys.argv) == 2:
        test_case = '.' + sys.argv[1]
    elif len(sys.argv) == 1:
        test_case = ''
    else:
        print(usage())
        sys.exit(1)

    patch_for_test_db_setup()
    failures = test_runner.run_tests(['tests' + test_case])

    sys.exit(failures)
Esempio n. 48
0
def configure(**extra):
    from django.conf import settings
    os.environ['DJANGO_SETTINGS_MODULE'] = 'filer.test_utils.cli'
    defaults = dict(
        DEBUG=True,
        TEMPLATE_DEBUG=True,
        DATABASE_SUPPORTS_TRANSACTIONS=True,
        DATABASES={'default': {
            'ENGINE': 'django.db.backends.sqlite3'
        }},
        USE_I18N=True,
        MEDIA_ROOT='/media/',
        STATIC_ROOT='/static/',
        MEDIA_URL='/media/',
        STATIC_URL='/static/',
        EMAIL_BACKEND='django.core.mail.backends.locmem.EmailBackend',
        SECRET_KEY='key',
        TEMPLATE_LOADERS=(
            'django.template.loaders.filesystem.Loader',
            'django.template.loaders.app_directories.Loader',
            'django.template.loaders.eggs.Loader',
        ),
        SOUTH_TESTS_MIGRATE=True,
        INSTALLED_APPS=[
            'django.contrib.auth',
            'django.contrib.contenttypes',
            'django.contrib.admin',
            'django.contrib.sessions',
            'django.contrib.staticfiles',
            'easy_thumbnails',
            'mptt',
            'filer',
            'south',
        ],
        ROOT_URLCONF='filer.test_utils.cli',
    )
    if ET_2:
        extra['SOUTH_MIGRATION_MODULES'] = {
            'easy_thumbnails': 'easy_thumbnails.south_migrations',
        }

    defaults.update(extra)
    settings.configure(**defaults)
    from south.management.commands import patch_for_test_db_setup
    patch_for_test_db_setup()
    from django.contrib import admin
    admin.autodiscover()
def before_all(context):
    settings = chroma_settings()
    from django.core.management import setup_environ
    setup_environ(settings)

    ### Take a TestRunner hostage.
    # Use django_nose's runner so that we can take advantage of REUSE_DB=1.
    from django_nose import NoseTestSuiteRunner
    # We'll use these later to frog-march Django through the motions
    # of setting up and tearing down the test environment, including
    # test databases.
    context.runner = NoseTestSuiteRunner()

    ## 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()
Esempio n. 50
0
def setup_database(actual_server):
	'''
	This will setup your database, sync it, and run migrations if you are using South.
	It does this before the Test Django server is set up.
	'''
	logger.info("Setting up a test database...")

	# Uncomment if you are using South
	patch_for_test_db_setup()

	world.test_runner = DjangoTestSuiteRunner(interactive=False)
	DjangoTestSuiteRunner.setup_test_environment(world.test_runner)
	world.created_db = DjangoTestSuiteRunner.setup_databases(world.test_runner)

	call_command('syncdb', interactive=False, verbosity=0)

	# Uncomment if you are using South
	call_command('migrate', interactive=False, verbosity=0)
Esempio n. 51
0
    def __init__(self, *args, **kwargs):
        self.cov = coverage()
        self.cov.start()
        self.configure()
        self.packages = self.resolve_packages()

        parser = argparse.ArgumentParser()
        parser.add_argument('-a', '--autoreload', dest='autoreload',
                action='store_const', const=True, default=False,)
        parser.add_argument('-f', '--failfast', dest='failfast',
                action='store_const', const=True, default=False,)
        parser.add_argument('-l', '--label', dest='label')
        self.options = vars(parser.parse_args(sys.argv[2:]))
        sys.argv = sys.argv[:2]

        runner_options = {
            'verbosity': 1,
            'interactive': True,
            'failfast': False,
        }

        if django.VERSION >= (1, 8):
            from django.test.runner import DiscoverRunner
            self.test_runner = DiscoverRunner(**runner_options)
            tests = self.test_runner.build_suite()
        else:
            from django.test.simple import DjangoTestSuiteRunner
            self.test_runner = DjangoTestSuiteRunner(**runner_options)
            tests = self.build_tests()

        super(SetupTestSuite, self).__init__(tests=tests, *args, **kwargs)

        # South patches the test management command to handle the
        # SOUTH_TESTS_MIGRATE setting. Apply that patch if South is installed.
        if django.VERSION < (1,7):
            try:
                from south.management.commands import patch_for_test_db_setup
                patch_for_test_db_setup()
            except ImportError:
                pass
        self.test_runner.setup_test_environment()
        self.old_config = self.test_runner.setup_databases()
Esempio n. 52
0
def runtests(*test_args, **kwargs):
    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:
        test_args = ['djangoratings']

    import django
    try:
        django.setup()
    except AttributeError:
        pass

    kwargs.setdefault('interactive', False)

    test_runner = DiscoverRunner(**kwargs)

    failures = test_runner.run_tests(test_args)
    sys.exit(failures)
Esempio n. 53
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)
Esempio n. 54
0
def run_tests(*test_args):
    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:
        test_args = ['tests']

    # Run tests
    test_runner = NoseTestSuiteRunner(verbosity=1)

    c = coverage(source=['oscar_stripe'], omit=['*migrations*', '*tests*'])
    c.start()
    num_failures = test_runner.run_tests(test_args)
    c.stop()

    if num_failures > 0:
        sys.exit(num_failures)
    print "Generating HTML coverage report"
    c.html_report()
Esempio n. 55
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)
Esempio n. 56
0
def run_tests(*test_labels, **options):
    patch_for_test_db_setup()
    verbosity = int(options.get('verbosity', 1))
    interactive = options.get('interactive', True)
    failfast = options.get('failfast', False)
    nocolor = options.get('nocolor', False)
    TestSuiteRunner = get_runner(settings)

    class NewTestSuiteRunner(TestSuiteRunner):
        def run_suite(self, suite, **kwargs):
            return get_test_runner(nocolor)(
                verbosity=self.verbosity).run(suite)

        def suite_result(self, suite, result, **kwargs):
            return result

    test_runner = NewTestSuiteRunner(verbosity=verbosity,
                                     interactive=interactive,
                                     failfast=failfast)
    result = test_runner.run_tests(test_labels)
    return result
Esempio n. 57
0
def configure(**extra):
    from django.conf import settings
    defaults = dict(
        CACHE_BACKEND='locmem:///',
        DATABASES={
            'default': {
                'ENGINE': 'django.db.backends.sqlite3',
                'NAME': ':memory:',
            }
        },
        SOUTH_TESTS_MIGRATE=False,
        PASSWORD_HASHERS=(
            'django.contrib.auth.hashers.MD5PasswordHasher',
        )
    )
    defaults.update(extra)
    for key, value in defaults.items():
        setattr(settings, key, value)
    from south.management.commands import patch_for_test_db_setup
    patch_for_test_db_setup()
    logging.disable(logging.CRITICAL)
Esempio n. 58
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
Esempio n. 59
0
def _handle_south():
    from django.conf import settings

    # NOTE: Django 1.7 does not have `management._commands` anymore, which
    # is used by South's `patch_for_test_db_setup` and the code below.
    if 'south' not in settings.INSTALLED_APPS or get_django_version() > (1, 7):
        return

    from django.core import management

    try:
        # if `south` >= 0.7.1 we can use the test helper
        from south.management.commands import patch_for_test_db_setup
    except ImportError:
        # if `south` < 0.7.1 make sure its migrations are disabled
        management.get_commands()
        management._commands['syncdb'] = 'django.core'
    else:
        # Monkey-patch south.hacks.django_1_0.SkipFlushCommand to load
        # initial data.
        # Ref: http://south.aeracode.org/ticket/1395#comment:3
        import south.hacks.django_1_0
        from django.core.management.commands.flush import (Command as
                                                           FlushCommand)

        class SkipFlushCommand(FlushCommand):
            def handle_noargs(self, **options):
                # Reinstall the initial_data fixture.
                from django.core.management import call_command
                # `load_initial_data` got introduces with Django 1.5.
                load_initial_data = options.get('load_initial_data', None)
                if load_initial_data or load_initial_data is None:
                    # Reinstall the initial_data fixture.
                    call_command('loaddata', 'initial_data', **options)
                # no-op to avoid calling flush
                return

        south.hacks.django_1_0.SkipFlushCommand = SkipFlushCommand

        patch_for_test_db_setup()
Esempio n. 60
0
def runtests(*test_args, **kwargs):
    from django_nose import NoseTestSuiteRunner
    if 'south' in settings.INSTALLED_APPS:
        from south.management.commands import patch_for_test_db_setup
        patch_for_test_db_setup()

    test_args = test_args or []

    if 'verbosity' in kwargs:
        kwargs['verbosity'] = int(kwargs['verbosity'])

    kwargs.setdefault('interactive', False)

    test_args.append('--with-coverage')
    test_args.append('--cover-package=swingers')
    test_args.append('--cover-xml')
    test_args.append('--cover-xml-file=coverage.xml')

    test_runner = NoseTestSuiteRunner(**kwargs)

    failures = test_runner.run_tests(test_args)
    sys.exit(failures)