def enable(self): # Keep this code at the beginning to leave the settings unchanged # in case it raises an exception because INSTALLED_APPS is invalid. if 'INSTALLED_APPS' in self.options: try: apps.set_installed_apps(self.options['INSTALLED_APPS']) except Exception: apps.unset_installed_apps() raise override = UserSettingsHolder(settings._wrapped) for key, new_value in self.options.items(): setattr(override, key, new_value) # 保存原有的配置 self.wrapped = settings._wrapped settings._wrapped = override for key, new_value in self.options.items(): setting_changed.send( sender=settings._wrapped.__class__, setting=key, value=new_value, enter=True)
def test_PG_EXTRA_SEARCH_PATHS(self): del apps.all_models['django_tenants'] c = connection.cursor() c.execute('DROP SCHEMA {0} CASCADE; CREATE SCHEMA {0};'.format( get_public_schema_name() )) apps.set_installed_apps(['customers', 'django_tenants'])
def setUp(self): super(TestModelsLoaderMixin, self).setUp() # If we made a fake 'models' module, add it to sys.modules. models_mod = self._tests_loader_models_mod if models_mod: sys.modules[models_mod.__name__] = models_mod self._models_loader_old_settings = settings.INSTALLED_APPS settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + [ self.tests_app, ] if apps: # Push the new set of installed apps, and begin registering # each of the models associated with the tests. apps.set_installed_apps(settings.INSTALLED_APPS) app_config = apps.get_containing_app_config(self.tests_app) if models_mod: for key, value in six.iteritems(models_mod.__dict__): if inspect.isclass(value) and issubclass(value, Model): apps.register_model(app_config.label, value) call_command('migrate', verbosity=0, interactive=False) else: load_app(self.tests_app) call_command('syncdb', verbosity=0, interactive=False)
def setup_run_tests(verbosity, start_at, start_after, test_labels=None): test_modules, state = setup_collect_tests(start_at, start_after, test_labels=test_labels) installed_apps = set(get_installed()) for app in get_apps_to_install(test_modules): if app in installed_apps: continue if verbosity >= 2: print(f'Importing application {app}') settings.INSTALLED_APPS.append(app) installed_apps.add(app) apps.set_installed_apps(settings.INSTALLED_APPS) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception( 'Please define available_apps in TransactionTestCase and its ' 'subclasses.') TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None # Set an environment variable that other code may consult to see if # Django's own test suite is running. os.environ['RUNNING_DJANGOS_TEST_SUITE'] = 'true' test_labels = test_labels or test_modules return test_labels, state
def setUp(self): super(TestModelsLoaderMixin, self).setUp() # If we made a fake 'models' module, add it to sys.modules. models_mod = self._tests_loader_models_mod if models_mod: sys.modules[models_mod.__name__] = models_mod self._models_loader_old_settings = settings.INSTALLED_APPS settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + [ self.tests_app, ] if apps: # Push the new set of installed apps, and begin registering # each of the models associated with the tests. apps.set_installed_apps(settings.INSTALLED_APPS) app_config = apps.get_containing_app_config(self.tests_app) for key, value in six.iteritems(models_mod.__dict__): if inspect.isclass(value) and issubclass(value, Model): apps.register_model(app_config.label, value) call_command('migrate', verbosity=0, interactive=False) else: load_app(self.tests_app) call_command('syncdb', verbosity=0, interactive=False)
def enable(self): # Keep this code at the beginning to leave the settings unchanged # in case it raises an exception because INSTALLED_APPS is invalid. if 'INSTALLED_APPS' in self.options: try: apps.set_installed_apps(self.options['INSTALLED_APPS']) except Exception: apps.unset_installed_apps() raise override = UserSettingsHolder(settings._wrapped) for key, new_value in self.options.items(): setattr(override, key, new_value) self.wrapped = settings._wrapped settings._wrapped = override for key, new_value in self.options.items(): try: setting_changed.send( sender=settings._wrapped.__class__, setting=key, value=new_value, enter=True, ) except Exception as exc: self.enable_exception = exc self.disable()
def setup(verbosity, test_labels): state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATES': settings.TEMPLATES, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, MIDDLEWARE_ATTR: getattr(settings, MIDDLEWARE_ATTR), } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = '' settings.TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR)], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.debug', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', ], }, }] settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 setattr(settings, MIDDLEWARE_ATTR, ALWAYS_MIDDLEWARE_CLASSES) # Ensure the middleware classes are seen as overridden otherwise we get a compatibility warning. settings._explicit_settings.add(MIDDLEWARE_ATTR) settings.MIGRATION_MODULES = { 'auth': None, 'contenttypes': None, 'sessions': None, 'autocomplete': None, } # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load the test model apps. if not test_labels: modules = get_test_modules() else: modules = set([label.split(".")[0] for label in test_labels]) for module_label in modules: settings.INSTALLED_APPS.append(module_label) apps.set_installed_apps(settings.INSTALLED_APPS) return state
def main(): """ Standalone django model test with a 'memory-only-django-installation'. You can play with a django model without a complete django app installation. http://www.djangosnippets.org/snippets/1044/ """ os.environ["DJANGO_SETTINGS_MODULE"] = "django.conf.global_settings" from django.conf import global_settings global_settings.INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.sessions', 'django.contrib.contenttypes', 'storages', ) if django.VERSION > (1,2): global_settings.DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_PATH, 'connpass.sqlite'), 'USER': '', 'PASSWORD': '', 'HOST': '', 'PORT': '', } } else: global_settings.DATABASE_ENGINE = "sqlite3" global_settings.DATABASE_NAME = ":memory:" global_settings.ROOT_URLCONF='beproud.django.authutils.tests.test_urls' global_settings.MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'beproud.django.authutils.middleware.AuthMiddleware', ) global_settings.DEFAULT_FILE_STORAGE = 'backends.s3boto.S3BotoStorage' global_settings.AWS_IS_GZIPPED = True global_settings.SECRET_KEY = "tralala" if django.VERSION >= (1,7): django.setup() apps.set_installed_apps(global_settings.INSTALLED_APPS) from django.test.utils import get_runner test_runner = get_runner(global_settings) if django.VERSION > (1,2): test_runner = test_runner() failures = test_runner.run_tests(['storages']) else: failures = test_runner(['storages'], verbosity=1) sys.exit(failures)
def setUp(self): admin = 'django.contrib.admin' noadmin_apps = [app for app in installed_apps() if not app == admin] try: from django.apps import apps apps.set_installed_apps(noadmin_apps) except ImportError: self._ctx = SettingsOverride(INSTALLED_APPS=noadmin_apps) self._ctx.__enter__()
def setup_databases(self, **kwargs): # Look for test models test_apps = set() for package in self.test_packages: if find_spec('.models', package): test_apps.add(package) # Add test apps with models to INSTALLED_APPS that aren't already there new_installed = settings.INSTALLED_APPS + tuple( ta for ta in test_apps if ta not in settings.INSTALLED_APPS) apps.set_installed_apps(new_installed) return super().setup_databases(**kwargs)
def setup(test_labels): # Reduce the given test labels to just the app module path. test_labels_set = set() for label in test_labels: bits = label.split('.')[:1] test_labels_set.add('.'.join(bits)) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATES': settings.TEMPLATES, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE': settings.MIDDLEWARE, } # Redirect some settings for the duration of these tests. # settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TMPDIR, 'static') settings.TEMPLATES = [] settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIGRATION_MODULES = { # This lets us skip creating migrations for the test models as many of # them depend on one of the following contrib applications. 'auth': None, 'contenttypes': None, 'sessions': None, } settings.SILENCED_SYSTEM_CHECKS = [ 'fields.W342', # ForeignKey(unique=True) -> OneToOneField ] # Load all the ALWAYS_INSTALLED_APPS. django.setup() apps.set_installed_apps(settings.INSTALLED_APPS) return state
def run_app_tests(app_name): print(f"Running tests for app `{app_name}`") state = { "INSTALLED_APPS": [*settings.INSTALLED_APPS], "ROOT_URLCONF": getattr(settings, "ROOT_URLCONF", ""), "TEMPLATES": settings.TEMPLATES, "LANGUAGE_CODE": settings.LANGUAGE_CODE, "STATIC_URL": settings.STATIC_URL, "STATIC_ROOT": settings.STATIC_ROOT, "MIDDLEWARE": settings.MIDDLEWARE, } try: # Check if this app defines a custom settings configuration. settings_path = f"{app_name}.tests.config.test_settings" if importlib.util.find_spec(settings_path): app_settings = importlib.import_module(settings_path) if hasattr(app_settings, "INSTALLED_APPS"): settings.INSTALLED_APPS += [*app_settings.INSTALLED_APPS] if hasattr(app_settings, "ROOT_URLCONF"): settings.ROOT_URLCONF = app_settings.ROOT_URLCONF if hasattr(app_settings, "MIDDLEWARE"): settings.MIDDLEWARE = app_settings.MIDDLEWARE except ModuleNotFoundError: pass settings.INSTALLED_APPS.append(app_name) # Ensure there are no duplicates settings.INSTALLED_APPS = list(set(settings.INSTALLED_APPS)) print(f"INSTALLED_APPS: {settings.INSTALLED_APPS}") apps.set_installed_apps(settings.INSTALLED_APPS) test_runner = VerboseTestRunner() test_results = test_runner.run_tests([f"{app_name}.tests"]) from django.contrib.contenttypes.models import ContentType ContentType.objects.clear_cache() _reset_settings(state) apps.unset_installed_apps() return test_results
def _call_test_func(self, test_fn): apps = None need_to_call_unset = False if django.get_version() >= '1.7': from django.apps import apps if not apps.is_installed('djangular.config.angularseed_template'): apps.set_installed_apps(tuple([ 'djangular.config.angularseed_template'])) need_to_call_unset = True try: test_fn(self) finally: if apps and need_to_call_unset: apps.unset_installed_apps()
def _call_test_func(self, test_fn): apps = None need_to_call_unset = False if django.VERSION >= (1, 7): from django.apps import apps if not apps.is_installed('djangular.config.angularseed_template'): apps.set_installed_apps( tuple(['djangular.config.angularseed_template'])) need_to_call_unset = True try: test_fn(self) finally: if apps and need_to_call_unset: apps.unset_installed_apps()
def optimize_apps_for_test_labels(test_labels): test_map = AppAndTestMap() for label in test_labels: if "." in label: test_map.add_test(label.split(".")[0], build_test(label)) else: test_map.add_app(label) _real_installed_apps = settings.INSTALLED_APPS needed_apps = test_map.get_needed_installed_apps() print "overriding settings.INSTALLED_APPS to {}".format(",".join(test_map.get_needed_installed_apps())) settings.INSTALLED_APPS = tuple(needed_apps) apps.set_installed_apps(settings.INSTALLED_APPS) try: yield finally: settings.INSTALLED_APPS = _real_installed_apps apps.unset_installed_apps()
def setUp(self): super(TestModelsLoaderMixin, self).setUp() # If we made a fake 'models' module, add it to sys.modules. models_mod = self._tests_loader_models_mod if models_mod: sys.modules[models_mod.__name__] = models_mod self._models_loader_old_settings = settings.INSTALLED_APPS settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + [ self.tests_app, ] if apps: # Push the new set of installed apps, and begin registering # each of the models associated with the tests. apps.set_installed_apps(settings.INSTALLED_APPS) app_config = apps.get_containing_app_config(self.tests_app) if models_mod: app_label = app_config.label for key, value in six.iteritems(models_mod.__dict__): if inspect.isclass(value) and issubclass(value, Model): # The model was likely registered under another app, # so we need to remove the old one and add the new # one. try: del apps.all_models[value._meta.app_label][ value._meta.model_name] except KeyError: pass value._meta.app_label = app_label apps.register_model(app_label, value) call_command('migrate', run_syncdb=True, verbosity=0, interactive=False) else: load_app(self.tests_app) call_command('syncdb', verbosity=0, interactive=False)
def setup(self, verbosity, testLabels): # Force declaring available_apps in TransactionTestCase for faster # tests. def noAvailableApps(self): raise Exception('Please define available_apps in' ' TransactionTestCase and its subclasses.') TransactionTestCase.available_apps = property(noAvailableApps) TestCase.available_apps = None state = self.prepareSettings(settings) if verbosity > 0: # Ensure any warnings captured to logging are piped through a # verbose logging handler. If any -W options were passed # explicitly on command line, warnings are not captured, and # this has no effect. logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) # Load all the self.alwaysInstalledApps. django.setup() # Reduce given test labels to just the app module path appNames = set(l.split('.', 1)[0] for l in testLabels) # Load all the test model apps. if verbosity >= 2: self.stream.writeln('Importing applications ...') for name in appNames: if verbosity >= 2: self.stream.writeln('Importing application {0}'.format(name)) module = importlib.import_module(name) config = AppConfig(name, module) config.label = '_'.join((config.label.strip('_'), 'tests')) settings.INSTALLED_APPS.append(config) apps.set_installed_apps(settings.INSTALLED_APPS) return state
def optimize_apps_for_test_labels(test_labels): # TODO make this work on Django 1.8 (django.test.simple has been removed) from django.test.simple import build_test test_map = AppAndTestMap() for label in test_labels: if isinstance(label, tuple): test_map.add_test(*label) elif '.' in label: test_map.add_test(label.split('.')[0], build_test(label)) else: test_map.add_app(label) _real_installed_apps = settings.INSTALLED_APPS needed_apps = test_map.get_needed_installed_apps() print 'overriding settings.INSTALLED_APPS to {}'.format(','.join( test_map.get_needed_installed_apps())) settings.INSTALLED_APPS = tuple(needed_apps) apps.set_installed_apps(settings.INSTALLED_APPS) try: yield finally: settings.INSTALLED_APPS = _real_installed_apps apps.unset_installed_apps()
def run_migrations(self, schema_name, included_apps): self._notice("=== Running migrate for schema %s" % schema_name) connection.set_schema(schema_name, include_public=False) apps.app_configs = OrderedDict() apps.clear_cache() apps.set_installed_apps(included_apps) command = MigrateCommand() defaults = {} for opt in MigrateCommand.option_list: if opt.dest in self.options: defaults[opt.dest] = self.options[opt.dest] elif opt.default is NO_DEFAULT: defaults[opt.dest] = None else: defaults[opt.dest] = opt.default command.execute(*self.args, **defaults) connection.set_schema('public', include_public=True) apps.app_configs = OrderedDict() apps.clear_cache() apps.set_installed_apps(settings.SHARED_APPS)
def optimize_apps_for_test_labels(test_labels): # TODO make this work on Django 1.8 (django.test.simple has been removed) from django.test.simple import build_test test_map = AppAndTestMap() for label in test_labels: if isinstance(label, tuple): test_map.add_test(*label) elif '.' in label: test_map.add_test(label.split('.')[0], build_test(label)) else: test_map.add_app(label) _real_installed_apps = settings.INSTALLED_APPS needed_apps = test_map.get_needed_installed_apps() print 'overriding settings.INSTALLED_APPS to {}'.format( ','.join(test_map.get_needed_installed_apps()) ) settings.INSTALLED_APPS = tuple(needed_apps) apps.set_installed_apps(settings.INSTALLED_APPS) try: yield finally: settings.INSTALLED_APPS = _real_installed_apps apps.unset_installed_apps()
def setup(verbosity, test_labels): print("Testing against Django installed in '%s'" % os.path.dirname(django.__file__)) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static') settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),) settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIDDLEWARE_CLASSES = ALWAYS_MIDDLEWARE_CLASSES # Ensure the middleware classes are seen as overridden otherwise we get a compatibility warning. settings._explicit_settings.add('MIDDLEWARE_CLASSES') settings.MIGRATION_MODULES = { # these 'tests.migrations' modules don't actually exist, but this lets # us skip creating migrations for the test models. 'auth': 'django.contrib.auth.tests.migrations', 'contenttypes': 'django.contrib.contenttypes.tests.migrations', } if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. If any -W options were passed explicitly on command # line, warnings are not captured, and this has no effect. logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) warnings.filterwarnings( 'ignore', 'django.contrib.webdesign will be removed in Django 2.0.', RemovedInDjango20Warning ) # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split('.') if bits[:2] == ['django', 'contrib']: bits = bits[:3] else: bits = bits[:1] test_labels_set.add('.'.join(bits)) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = '.'.join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + '.') for label in test_labels_set) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) apps.set_installed_apps(settings.INSTALLED_APPS) return state
def setup(verbosity, test_labels, parallel): if verbosity >= 1: msg = "Testing against Django installed in '%s'" % os.path.dirname( django.__file__) max_parallel = default_test_processes() if parallel == 0 else parallel if max_parallel > 1: msg += " with up to %d processes" % max_parallel print(msg) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATES': settings.TEMPLATES, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TMPDIR, 'static') settings.TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }] settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIDDLEWARE_CLASSES = ALWAYS_MIDDLEWARE_CLASSES settings.MIGRATION_MODULES = { # This lets us skip creating migrations for the test models as many of # them depend on one of the following contrib applications. 'auth': None, 'contenttypes': None, 'sessions': None, } log_config = copy.deepcopy(DEFAULT_LOGGING) # Filter out non-error logging so we don't have to capture it in lots of # tests. log_config['loggers']['django']['level'] = 'ERROR' settings.LOGGING = log_config warnings.filterwarnings('ignore', 'The GeoManager class is deprecated.', RemovedInDjango20Warning) # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split('.')[:1] test_labels_set.add('.'.join(bits)) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = '.'.join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + '.') for label in test_labels_set) if module_name in CONTRIB_TESTS_TO_APPS and module_found_in_labels: settings.INSTALLED_APPS.append(CONTRIB_TESTS_TO_APPS[module_name]) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring # @override_settings(INSTALLED_APPS=...) on all test cases. gis = 'django.contrib.gis' if connection.features.gis_enabled and gis not in settings.INSTALLED_APPS: if verbosity >= 2: print("Importing application %s" % gis) settings.INSTALLED_APPS.append(gis) apps.set_installed_apps(settings.INSTALLED_APPS) return state
def setup(verbosity, test_labels): if verbosity >= 1: print("Testing against Django installed in '%s'" % os.path.dirname(django.__file__)) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), # Remove the following line in Django 2.0. 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, 'TEMPLATES': settings.TEMPLATES, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TMPDIR, 'static') # Remove the following line in Django 2.0. settings.TEMPLATE_DIRS = [TEMPLATE_DIR] settings.TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }] settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIDDLEWARE_CLASSES = ALWAYS_MIDDLEWARE_CLASSES settings.MIGRATION_MODULES = { # these 'tests.migrations' modules don't actually exist, but this lets # us skip creating migrations for the test models. 'auth': 'django.contrib.auth.tests.migrations', 'contenttypes': 'contenttypes_tests.migrations', } if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. If any -W options were passed explicitly on command # line, warnings are not captured, and this has no effect. logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) warnings.filterwarnings( 'ignore', 'django.contrib.webdesign will be removed in Django 2.0.', RemovedInDjango20Warning ) # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split('.')[:1] test_labels_set.add('.'.join(bits)) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = '.'.join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + '.') for label in test_labels_set) if module_name in CONTRIB_TESTS_TO_APPS and module_found_in_labels: settings.INSTALLED_APPS.append(CONTRIB_TESTS_TO_APPS[module_name]) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring # @override_settings(INSTALLED_APPS=...) on all test cases. gis = 'django.contrib.gis' if connection.features.gis_enabled and gis not in settings.INSTALLED_APPS: if verbosity >= 2: print("Importing application %s" % gis) settings.INSTALLED_APPS.append(gis) apps.set_installed_apps(settings.INSTALLED_APPS) return state
def setup(verbosity, test_labels, parallel): # Reduce the given test labels to just the app module path. test_labels_set = set() for label in test_labels: bits = label.split('.')[:1] test_labels_set.add('.'.join(bits)) if verbosity >= 1: msg = "Testing against Django installed in '%s'" % os.path.dirname(django.__file__) max_parallel = default_test_processes() if parallel == 0 else parallel if max_parallel > 1: msg += " with up to %d processes" % max_parallel print(msg) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATES': settings.TEMPLATES, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE': settings.MIDDLEWARE, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TMPDIR, 'static') settings.TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }] settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIDDLEWARE = ALWAYS_MIDDLEWARE settings.MIGRATION_MODULES = { # This lets us skip creating migrations for the test models as many of # them depend on one of the following contrib applications. 'auth': None, 'contenttypes': None, 'sessions': None, } log_config = copy.deepcopy(DEFAULT_LOGGING) # Filter out non-error logging so we don't have to capture it in lots of # tests. log_config['loggers']['django']['level'] = 'ERROR' settings.LOGGING = log_config settings.SILENCED_SYSTEM_CHECKS = [ 'fields.W342', # ForeignKey(unique=True) -> OneToOneField ] # Load all the ALWAYS_INSTALLED_APPS. django.setup() # It would be nice to put this validation earlier but it must come after # django.setup() so that connection.features.gis_enabled can be accessed # without raising AppRegistryNotReady when running gis_tests in isolation # on some backends (e.g. PostGIS). if 'gis_tests' in test_labels_set and not connection.features.gis_enabled: print('Aborting: A GIS database backend is required to run gis_tests.') sys.exit(1) # Load all the test model apps. test_modules = get_test_modules() installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = modpath + '.' + module_name else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + '.') for label in test_labels_set) if module_name in CONTRIB_TESTS_TO_APPS and module_found_in_labels: settings.INSTALLED_APPS.append(CONTRIB_TESTS_TO_APPS[module_name]) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring # @override_settings(INSTALLED_APPS=...) on all test cases. gis = 'django.contrib.gis' if connection.features.gis_enabled and gis not in settings.INSTALLED_APPS: if verbosity >= 2: print("Importing application %s" % gis) settings.INSTALLED_APPS.append(gis) apps.set_installed_apps(settings.INSTALLED_APPS) return state
def setup(verbosity, test_labels, parallel): # Reduce the given test labels to just the app module path. test_labels_set = set() for label in test_labels: bits = label.split('.')[:1] test_labels_set.add('.'.join(bits)) if verbosity >= 1: msg = "Testing against Django installed in '%s'" % os.path.dirname( django.__file__) max_parallel = default_test_processes() if parallel == 0 else parallel if max_parallel > 1: msg += " with up to %d processes" % max_parallel print(msg) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATES': settings.TEMPLATES, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE': settings.MIDDLEWARE, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'tests.urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TMPDIR, 'static') settings.TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }] settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIDDLEWARE = ALWAYS_MIDDLEWARE settings.MIGRATION_MODULES = { # This lets us skip creating migrations for the test models as many of # them depend on one of the following contrib applications. 'auth': None, 'contenttypes': None, 'sessions': None, } log_config = copy.deepcopy(DEFAULT_LOGGING) # Filter out non-error logging so we don't have to capture it in lots of # tests. log_config['loggers']['django']['level'] = 'ERROR' settings.LOGGING = log_config settings.SILENCED_SYSTEM_CHECKS = [ 'fields.W342', # ForeignKey(unique=True) -> OneToOneField ] # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load all the test model apps. apps.set_installed_apps(settings.INSTALLED_APPS) return state
def setup(verbosity, test_labels, start_at, start_after): # Reduce the given test labels to just the app module path. test_labels_set = set() for label in test_labels: bits = label.split('.')[:1] test_labels_set.add('.'.join(bits)) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATES': settings.TEMPLATES, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE': settings.MIDDLEWARE, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = 'static/' settings.STATIC_ROOT = os.path.join(TMPDIR, 'static') settings.TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }] settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIDDLEWARE = ALWAYS_MIDDLEWARE settings.MIGRATION_MODULES = { # This lets us skip creating migrations for the test models as many of # them depend on one of the following contrib applications. 'auth': None, 'contenttypes': None, 'sessions': None, } log_config = copy.deepcopy(DEFAULT_LOGGING) # Filter out non-error logging so we don't have to capture it in lots of # tests. log_config['loggers']['django']['level'] = 'ERROR' settings.LOGGING = log_config settings.SILENCED_SYSTEM_CHECKS = [ 'fields.W342', # ForeignKey(unique=True) -> OneToOneField ] # Load all the ALWAYS_INSTALLED_APPS. django.setup() # It would be nice to put this validation earlier but it must come after # django.setup() so that connection.features.gis_enabled can be accessed # without raising AppRegistryNotReady when running gis_tests in isolation # on some backends (e.g. PostGIS). if 'gis_tests' in test_labels_set and not connection.features.gis_enabled: print('Aborting: A GIS database backend is required to run gis_tests.') sys.exit(1) def _module_match_label(module_label, label): # Exact or ancestor match. return module_label == label or module_label.startswith(label + '.') # Load all the test model apps. test_modules = get_test_modules() found_start = not (start_at or start_after) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = modpath + '.' + module_name else: module_label = module_name if not found_start: if start_at and _module_match_label(module_label, start_at): found_start = True elif start_after and _module_match_label(module_label, start_after): found_start = True continue else: continue # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. module_found_in_labels = not test_labels or any( _module_match_label(module_label, label) for label in test_labels_set) if module_name in CONTRIB_TESTS_TO_APPS and module_found_in_labels: for contrib_app in CONTRIB_TESTS_TO_APPS[module_name]: if contrib_app not in settings.INSTALLED_APPS: settings.INSTALLED_APPS.append(contrib_app) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring # @override_settings(INSTALLED_APPS=...) on all test cases. gis = 'django.contrib.gis' if connection.features.gis_enabled and gis not in settings.INSTALLED_APPS: if verbosity >= 2: print("Importing application %s" % gis) settings.INSTALLED_APPS.append(gis) apps.set_installed_apps(settings.INSTALLED_APPS) # Set an environment variable that other code may consult to see if # Django's own test suite is running. os.environ['RUNNING_DJANGOS_TEST_SUITE'] = 'true' return state
def main(modules, verbosity=2, failfast=False, contrib=None, nocontrib=False): print('python ' + sys.version) print('django ' + django.get_version()) print('*' * 80) # run flake8 first styleguide = get_style_guide( # TODO: Check if we can read a config file # parse_argv=False, # config_file="setup.cfg", ignore=["T000"], max_complexity=-1, doctests=False, max_line_length=120, exclude=[ '__pycache__', '.git', '.tox', 'virtenv', '*egg', 'migrations', ], paths = [ "djangobmf", "tests", ] ) styleguide.options.report.start() styleguide.options.report.stop() if styleguide.options.report.get_count() > 0: sys.exit(True) # apply test settings TEMP_DIR = tempfile.mkdtemp(prefix='djangobmf_') settings.BMF_DOCUMENT_ROOT = TEMP_DIR settings.BMF_DOCUMENT_URL = '/documents/' if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) # Load all the app django.setup() # only test one contrib module if contrib: modules = ["djangobmf.contrib.%s" % contrib] # find tests in tests-directory if len(modules) == 0: path = os.path.join(os.path.dirname(__file__), "tests") for module in os.listdir(path): if os.path.isdir(os.path.join(path, module)) and module[0] != '_': modules.append('tests.%s' % module) # find tests in contrib modules SKIPDIRS = [] if not nocontrib: path = bmfcontrib.__path__[0] for module in os.listdir(path): if os.path.isdir(os.path.join(path, module)): if module[0] == '_' or module in SKIPDIRS: continue modules.append('djangobmf.contrib.%s' % module) # add currencies to INSTALLED_APPS path = bmfcurrencies.__path__[0] for module in os.listdir(path): if os.path.isdir(os.path.join(path, module)): if module[0] == '_': continue settings.INSTALLED_APPS += ('djangobmf.currency.%s' % module, ) # update installed apps installed_app_names = set(get_installed()) for module in modules: if module not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module) settings.INSTALLED_APPS += (module, ) apps.set_installed_apps(settings.INSTALLED_APPS) # Load default settings from bmf framework from djangobmf.conf import settings as bmfsettings bmfsettings.patch() failures = djangobmf_tests(verbosity, False, failfast, modules) try: # Removing the temporary TEMP_DIR. Ensure we pass in unicode # so that it will successfully remove temp trees containing # non-ASCII filenames on Windows. (We're assuming the temp dir # name itself does not contain non-ASCII characters.) shutil.rmtree(six.text_type(TEMP_DIR)) except OSError: print('Failed to remove temp directory: %s' % TEMP_DIR) sys.exit(bool(failures))
def setup(verbosity, test_labels): print("Testing against Django installed in '%s'" % os.path.dirname(django.__file__)) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { "INSTALLED_APPS": settings.INSTALLED_APPS, "ROOT_URLCONF": getattr(settings, "ROOT_URLCONF", ""), "TEMPLATE_DIRS": settings.TEMPLATE_DIRS, "LANGUAGE_CODE": settings.LANGUAGE_CODE, "STATIC_URL": settings.STATIC_URL, "STATIC_ROOT": settings.STATIC_ROOT, "MIDDLEWARE_CLASSES": settings.MIDDLEWARE_CLASSES, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = "urls" settings.STATIC_URL = "/static/" settings.STATIC_ROOT = os.path.join(TEMP_DIR, "static") settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),) settings.LANGUAGE_CODE = "en" settings.SITE_ID = 1 settings.MIDDLEWARE_CLASSES = ALWAYS_MIDDLEWARE_CLASSES # Ensure the middleware classes are seen as overridden otherwise we get a compatibility warning. settings._explicit_settings.add("MIDDLEWARE_CLASSES") if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. If any -W options were passed explicitly on command # line, warnings are not captured, and this has no effect. logger = logging.getLogger("py.warnings") handler = logging.StreamHandler() logger.addHandler(handler) # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split(".") if bits[:2] == ["django", "contrib"]: bits = bits[:3] else: bits = bits[:1] test_labels_set.add(".".join(bits)) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = ".".join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + ".") for label in test_labels_set ) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) apps.set_installed_apps(settings.INSTALLED_APPS) return state
def setup(verbosity, test_labels): print("Testing against Django installed in '%s'" % os.path.dirname(django.__file__)) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { "INSTALLED_APPS": settings.INSTALLED_APPS, "ROOT_URLCONF": getattr(settings, "ROOT_URLCONF", ""), "TEMPLATES": settings.TEMPLATES, "LANGUAGE_CODE": settings.LANGUAGE_CODE, "STATIC_URL": settings.STATIC_URL, "STATIC_ROOT": settings.STATIC_ROOT, "MIDDLEWARE_CLASSES": settings.MIDDLEWARE_CLASSES, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = "urls" settings.STATIC_URL = "/static/" settings.STATIC_ROOT = os.path.join(TMPDIR, "static") settings.TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [TEMPLATE_DIR], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ] }, } ] settings.LANGUAGE_CODE = "en" settings.SITE_ID = 1 settings.MIDDLEWARE_CLASSES = ALWAYS_MIDDLEWARE_CLASSES # Ensure the middleware classes are seen as overridden otherwise we get a compatibility warning. settings._explicit_settings.add("MIDDLEWARE_CLASSES") settings.MIGRATION_MODULES = { # these 'tests.migrations' modules don't actually exist, but this lets # us skip creating migrations for the test models. "auth": "django.contrib.auth.tests.migrations", "contenttypes": "contenttypes_tests.migrations", } if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. If any -W options were passed explicitly on command # line, warnings are not captured, and this has no effect. logger = logging.getLogger("py.warnings") handler = logging.StreamHandler() logger.addHandler(handler) warnings.filterwarnings( "ignore", "django.contrib.webdesign will be removed in Django 1.10.", RemovedInDjango110Warning ) # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split(".")[:1] test_labels_set.add(".".join(bits)) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = ".".join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + ".") for label in test_labels_set ) if module_name in CONTRIB_TESTS_TO_APPS and module_found_in_labels: settings.INSTALLED_APPS.append(CONTRIB_TESTS_TO_APPS[module_name]) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring # @override_settings(INSTALLED_APPS=...) on all test cases. gis = "django.contrib.gis" if connection.features.gis_enabled and gis not in settings.INSTALLED_APPS: if verbosity >= 2: print("Importing application %s" % gis) settings.INSTALLED_APPS.append(gis) apps.set_installed_apps(settings.INSTALLED_APPS) return state
def main(modules, verbosity=2, failfast=False, contrib=None, nocontrib=False): print('python ' + sys.version) print('django ' + django.get_version()) print('*' * 80) # run flake8 first styleguide = get_style_guide( # TODO: Check if we can read a config file # parse_argv=False, # config_file="setup.cfg", ignore=["T000"], max_complexity=-1, doctests=False, max_line_length=120, exclude=[ '__pycache__', '.git', '.tox', 'virtenv', '*egg', 'migrations', ], paths=[ "djangobmf", "tests", ]) styleguide.options.report.start() styleguide.options.report.stop() if styleguide.options.report.get_count() > 0: sys.exit(True) # apply test settings TEMP_DIR = tempfile.mkdtemp(prefix='djangobmf_') settings.BMF_DOCUMENT_ROOT = TEMP_DIR settings.BMF_DOCUMENT_URL = '/documents/' if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) # Load all the app django.setup() # only test one contrib module if contrib: modules = ["djangobmf.contrib.%s" % contrib] # find tests in tests-directory if len(modules) == 0: path = os.path.join(os.path.dirname(__file__), "tests") for module in os.listdir(path): if os.path.isdir(os.path.join(path, module)) and module[0] != '_': modules.append('tests.%s' % module) # find tests in contrib modules SKIPDIRS = [] if not nocontrib: path = bmfcontrib.__path__[0] for module in os.listdir(path): if os.path.isdir(os.path.join(path, module)): if module[0] == '_' or module in SKIPDIRS: continue modules.append('djangobmf.contrib.%s' % module) # add currencies to INSTALLED_APPS path = bmfcurrencies.__path__[0] for module in os.listdir(path): if os.path.isdir(os.path.join(path, module)): if module[0] == '_': continue settings.INSTALLED_APPS += ('djangobmf.currency.%s' % module, ) # update installed apps installed_app_names = set(get_installed()) for module in modules: if module not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module) settings.INSTALLED_APPS += (module, ) apps.set_installed_apps(settings.INSTALLED_APPS) # Load default settings from bmf framework from djangobmf.conf import settings as bmfsettings bmfsettings.patch() failures = djangobmf_tests(verbosity, False, failfast, modules) try: # Removing the temporary TEMP_DIR. Ensure we pass in unicode # so that it will successfully remove temp trees containing # non-ASCII filenames on Windows. (We're assuming the temp dir # name itself does not contain non-ASCII characters.) shutil.rmtree(six.text_type(TEMP_DIR)) except OSError: print('Failed to remove temp directory: %s' % TEMP_DIR) sys.exit(bool(failures))
def setUpClass(cls): cls._tests_loader_models_mod = None if not cls.tests_app: cls.tests_app = cls.__module__ models_mod_name = '%s.models' % cls.tests_app try: models_mod = import_module(models_mod_name) except ImportError: # Set up a 'models' module, containing any models local to the # module that this TestCase is in. if ModuleSpec: # Python >= 3.4 # # It's not enough to simply create a module type. We need to # create a basic spec, and then we need to have the module # system create a module from it. There's a handy public # function to do this on Python 3.5, but Python 3.4 lacks a # public function. Fortunately, it's easy to call a private # one. spec = ModuleSpec(name=models_mod_name, loader=None) if module_from_spec: # Python >= 3.5 models_mod = module_from_spec(spec) else: # Python == 3.4 models_mod = \ importlib._bootstrap._SpecMethods(spec).create() assert models_mod else: # Python < 3.4 models_mod = types.ModuleType(str(models_mod_name)) # Django needs a value here. Doesn't matter what it is. models_mod.__file__ = '' # Transfer all the models over into this new module. module_name = cls.__module__ test_module = sys.modules[module_name] for key, value in six.iteritems(test_module.__dict__): if (inspect.isclass(value) and issubclass(value, Model) and value.__module__ == module_name): models_mod.__dict__[key] = value cls._tests_loader_models_mod = models_mod if models_mod: sys.modules[models_mod.__name__] = models_mod cls._models_loader_old_settings = settings.INSTALLED_APPS settings.INSTALLED_APPS = list(settings.INSTALLED_APPS) + [ cls.tests_app, ] # If Django Evolution is being used, we'll want to clear out any # recorded schema information so that it can be generated from # scratch when we set up the database. if (Evolution is not None and Version is not None and getattr(settings, 'DJANGO_EVOLUTION_ENABLED', True)): Version.objects.all().delete() Evolution.objects.all().delete() if apps: # Push the new set of installed apps, and begin registering # each of the models associated with the tests. apps.set_installed_apps(settings.INSTALLED_APPS) app_config = apps.get_containing_app_config(cls.tests_app) if models_mod: app_label = app_config.label for key, value in six.iteritems(models_mod.__dict__): if inspect.isclass(value) and issubclass(value, Model): # The model was likely registered under another app, # so we need to remove the old one and add the new # one. try: del apps.all_models[value._meta.app_label][ value._meta.model_name] except KeyError: pass value._meta.app_label = app_label apps.register_model(app_label, value) call_command('migrate', run_syncdb=True, verbosity=0, interactive=False) else: load_app(cls.tests_app) call_command('syncdb', verbosity=0, interactive=False) super(TestModelsLoaderMixin, cls).setUpClass()
import logging
def main(self, options): """Main function for running unit tests for the extension. Args: options (argparse.Namespace): Options set from the arguments. Returns: int: The command's exit code. """ module_names = options.module_names or [] os.environ[str('RB_TEST_MODULES')] = force_str(','.join(module_names)) os.chdir(options.tree_root) os.environ[str('RB_RUNNING_TESTS')] = str('1') from django import setup from django.apps import apps from django.conf import settings if not apps.ready: setup() installed_apps = list(settings.INSTALLED_APPS) # If an explicit extension is specified, then we'll want to grab its # list of apps. extension_class_name = options.extension_class if extension_class_name: module_name, class_name = extension_class_name.rsplit('.', 1) try: extension_class = getattr(import_module(module_name), class_name) except AttributeError: console.error('The provided extension class "%s" could not be ' 'found in %s' % (class_name, module_name)) return 1 except ImportError: console.error('The provided extension class module "%s" ' 'could not be found' % module_name) return 1 installed_apps += (extension_class.apps or [module_name.rsplit('.', 1)[0]]) if options.app_names: installed_apps += options.app_names if installed_apps != list(settings.INSTALLED_APPS): settings.INSTALLED_APPS = installed_apps apps.set_installed_apps(installed_apps) from reviewboard.test import RBTestRunner test_runner = RBTestRunner(test_packages=module_names, cover_packages=module_names, verbosity=1, needs_collect_static=False) # Don't use +=, as we don't want to modify the list on the class. # We want to create a new one on the instance. test_runner.nose_options = \ test_runner.nose_options + (options.test_options or []) failures = test_runner.run_tests(options.tests) if failures: return 1 else: return 0
def setup(verbosity, test_labels, parallel): if verbosity >= 1: msg = "Testing against Django installed in '%s'" % os.path.dirname(django.__file__) max_parallel = default_test_processes() if parallel == 0 else parallel if max_parallel > 1: msg += " with up to %d processes" % max_parallel print(msg) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATES': settings.TEMPLATES, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TMPDIR, 'static') settings.TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }] settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIDDLEWARE_CLASSES = ALWAYS_MIDDLEWARE_CLASSES settings.MIGRATION_MODULES = { # these 'tests.migrations' modules don't actually exist, but this lets # us skip creating migrations for the test models. 'auth': 'django.contrib.auth.tests.migrations', 'contenttypes': 'contenttypes_tests.migrations', 'sessions': 'sessions_tests.migrations', } log_config = copy.deepcopy(DEFAULT_LOGGING) # Filter out non-error logging so we don't have to capture it in lots of # tests. log_config['loggers']['django']['level'] = 'ERROR' settings.LOGGING = log_config warnings.filterwarnings( 'ignore', 'The GeoManager class is deprecated.', RemovedInDjango20Warning ) # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split('.')[:1] test_labels_set.add('.'.join(bits)) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = '.'.join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + '.') for label in test_labels_set) if module_name in CONTRIB_TESTS_TO_APPS and module_found_in_labels: settings.INSTALLED_APPS.append(CONTRIB_TESTS_TO_APPS[module_name]) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring # @override_settings(INSTALLED_APPS=...) on all test cases. gis = 'django.contrib.gis' if connection.features.gis_enabled and gis not in settings.INSTALLED_APPS: if verbosity >= 2: print("Importing application %s" % gis) settings.INSTALLED_APPS.append(gis) apps.set_installed_apps(settings.INSTALLED_APPS) return state
def setup(verbosity, test_labels): from django.apps import apps from django.conf import settings from django.test import TransactionTestCase, TestCase print("Testing against Django installed in '%s'" % os.path.dirname(django.__file__)) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static') settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),) settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIDDLEWARE_CLASSES = ALWAYS_MIDDLEWARE_CLASSES # Ensure the middleware classes are seen as overridden otherwise we get a compatibility warning. settings._explicit_settings.add('MIDDLEWARE_CLASSES') settings.MIGRATION_MODULES = { # these 'tests.migrations' modules don't actually exist, but this lets # us skip creating migrations for the test models. 'auth': 'django.contrib.auth.tests.migrations', 'contenttypes': 'django.contrib.contenttypes.tests.migrations', } if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. If any -W options were passed explicitly on command # line, warnings are not captured, and this has no effect. logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) warnings.filterwarnings( 'ignore', 'django.contrib.comments is deprecated and will be removed before Django 1.8.', RemovedInDjango18Warning ) warnings.filterwarnings( 'ignore', 'Model class django.contrib.comments.models.* Django 1.9.', RemovedInDjango19Warning ) # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split('.') if bits[:2] == ['django', 'contrib']: bits = bits[:3] else: bits = bits[:1] test_labels_set.add('.'.join(bits)) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = '.'.join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + '.') for label in test_labels_set) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) apps.set_installed_apps(settings.INSTALLED_APPS) return state
def setup(verbosity, test_labels): state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES, } settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'denyzen.tests.urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static') settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR),) settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIDDLEWARE_CLASSES = ALWAYS_MIDDLEWARE_CLASSES # Ensure the middleware classes are seen as overridden otherwise we get a compatibility warning. #settings._explicit_settings.add('MIDDLEWARE_CLASSES') settings.MIGRATION_MODULES = { # these 'tests.migrations' modules don't actually exist, but this lets # us skip creating migrations for the test models. 'auth': 'django.contrib.auth.tests.migrations', 'contenttypes': 'django.contrib.contenttypes.tests.migrations', } # Load all the ALWAYS_INSTALLED_APPS. django.setup() if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. If any -W options were passed explicitly on command # line, warnings are not captured, and this has no effect. logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) # Load all the test model apps. test_modules = get_test_modules() print(test_modules) test_labels_set = set() for label in test_labels: test_labels_set.add(label) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = '.'.join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + '.') for label in test_labels_set) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) app_config = AppConfig.create(module_name) apps.app_configs[app_config.label] = app_config app_config.import_models(apps.all_models[app_config.label]) apps.clear_cache() apps.set_installed_apps(settings.INSTALLED_APPS) return state
def setup(verbosity, test_labels): print("Testing against Django installed in '%s'" % os.path.dirname(django.__file__)) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), # Remove the following line in Django 2.0. 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, 'TEMPLATES': settings.TEMPLATES, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, 'MIDDLEWARE_CLASSES': settings.MIDDLEWARE_CLASSES, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TMPDIR, 'static') # Remove the following line in Django 2.0. settings.TEMPLATE_DIRS = (TEMPLATE_DIR, ) settings.TEMPLATES = [{ 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }] settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 settings.MIDDLEWARE_CLASSES = ALWAYS_MIDDLEWARE_CLASSES # Ensure the middleware classes are seen as overridden otherwise we get a compatibility warning. settings._explicit_settings.add('MIDDLEWARE_CLASSES') settings.MIGRATION_MODULES = { # these 'tests.migrations' modules don't actually exist, but this lets # us skip creating migrations for the test models. 'auth': 'django.contrib.auth.tests.migrations', 'contenttypes': 'contenttypes_tests.migrations', } if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. If any -W options were passed explicitly on command # line, warnings are not captured, and this has no effect. logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) warnings.filterwarnings( 'ignore', 'django.contrib.webdesign will be removed in Django 2.0.', RemovedInDjango20Warning) # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split('.')[:1] test_labels_set.add('.'.join(bits)) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = '.'.join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + '.') for label in test_labels_set) if module_name in CONTRIB_TESTS_TO_APPS and module_found_in_labels: settings.INSTALLED_APPS.append(CONTRIB_TESTS_TO_APPS[module_name]) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) # Add contrib.gis to INSTALLED_APPS if needed (rather than requiring # @override_settings(INSTALLED_APPS=...) on all test cases. gis = 'django.contrib.gis' if connection.features.gis_enabled and gis not in settings.INSTALLED_APPS: if verbosity >= 2: print("Importing application %s" % gis) settings.INSTALLED_APPS.append(gis) apps.set_installed_apps(settings.INSTALLED_APPS) return state
def setup(verbosity, test_labels, parallel): if verbosity >= 1: msg = f"Testing against django-site-metrics installed in '{os.path.dirname(metrics.__file__)}'" max_parallel = default_test_processes() if parallel == 0 else parallel if max_parallel > 1: msg += f" with up to {max_parallel} processes" print(msg) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception( "Please define available_apps in TransactionTestCase and its subclasses." ) TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { "INSTALLED_APPS": settings.INSTALLED_APPS, "ROOT_URLCONF": getattr(settings, "ROOT_URLCONF", ""), "TEMPLATES": settings.TEMPLATES, "LANGUAGE_CODE": settings.LANGUAGE_CODE, "STATIC_URL": settings.STATIC_URL, "STATIC_ROOT": settings.STATIC_ROOT, "MIDDLEWARE": settings.MIDDLEWARE, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = "urls" settings.STATIC_URL = "/static/" settings.STATIC_ROOT = os.path.join(TMPDIR, "static") settings.TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [TEMPLATE_DIR], "APP_DIRS": True, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", ], }, }, ] settings.LANGUAGE_CODE = "en" settings.SITE_ID = 1 settings.MIDDLEWARE = ALWAYS_MIDDLEWARE settings.MIGRATION_MODULES = { # This lets us skip creating migrations for the test models as many of # them depend on one of the following contrib applications. "auth": None, "contenttypes": None, "sessions": None, } log_config = copy.deepcopy(DEFAULT_LOGGING) # Filter out non-error logging so we don't have to capture it in lots of # tests. log_config["loggers"]["django"]["level"] = "ERROR" settings.LOGGING = log_config settings.SILENCED_SYSTEM_CHECKS = [ "fields.W342", # ForeignKey(unique=True) -> OneToOneField ] # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split(".")[:1] test_labels_set.add(".".join(bits)) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = ".".join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + ".") for label in test_labels_set) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print(f"Importing application {module_name}") settings.INSTALLED_APPS.append(module_label) apps.set_installed_apps(settings.INSTALLED_APPS) return state
def test_PG_EXTRA_SEARCH_PATHS(self): del apps.all_models['django_tenants'] c = connection.cursor() c.execute('DROP SCHEMA {0} CASCADE; CREATE SCHEMA {0};'.format( get_public_schema_name())) apps.set_installed_apps(['customers', 'django_tenants'])
def setup(verbosity, test_labels): print("Testing against Django installed in '%s'" % os.path.dirname(django.__file__)) # Force declaring available_apps in TransactionTestCase for faster tests. def no_available_apps(self): raise Exception("Please define available_apps in TransactionTestCase " "and its subclasses.") TransactionTestCase.available_apps = property(no_available_apps) TestCase.available_apps = None state = { 'INSTALLED_APPS': settings.INSTALLED_APPS, 'ROOT_URLCONF': getattr(settings, "ROOT_URLCONF", ""), 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, 'LANGUAGE_CODE': settings.LANGUAGE_CODE, 'STATIC_URL': settings.STATIC_URL, 'STATIC_ROOT': settings.STATIC_ROOT, } # Redirect some settings for the duration of these tests. settings.INSTALLED_APPS = ALWAYS_INSTALLED_APPS settings.ROOT_URLCONF = 'urls' settings.STATIC_URL = '/static/' settings.STATIC_ROOT = os.path.join(TEMP_DIR, 'static') settings.TEMPLATE_DIRS = (os.path.join(RUNTESTS_DIR, TEST_TEMPLATE_DIR), ) settings.LANGUAGE_CODE = 'en' settings.SITE_ID = 1 if verbosity > 0: # Ensure any warnings captured to logging are piped through a verbose # logging handler. If any -W options were passed explicitly on command # line, warnings are not captured, and this has no effect. logger = logging.getLogger('py.warnings') handler = logging.StreamHandler() logger.addHandler(handler) # Load all the ALWAYS_INSTALLED_APPS. django.setup() # Load all the test model apps. test_modules = get_test_modules() # Reduce given test labels to just the app module path test_labels_set = set() for label in test_labels: bits = label.split('.') if bits[:2] == ['django', 'contrib']: bits = bits[:3] else: bits = bits[:1] test_labels_set.add('.'.join(bits)) installed_app_names = set(get_installed()) for modpath, module_name in test_modules: if modpath: module_label = '.'.join([modpath, module_name]) else: module_label = module_name # if the module (or an ancestor) was named on the command line, or # no modules were named (i.e., run all), import # this module and add it to INSTALLED_APPS. if not test_labels: module_found_in_labels = True else: module_found_in_labels = any( # exact match or ancestor match module_label == label or module_label.startswith(label + '.') for label in test_labels_set) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) settings.INSTALLED_APPS.append(module_label) apps.set_installed_apps(settings.INSTALLED_APPS) return state