def dynamo_post_delete(sender, instance, **kwargs): """ Delete field from model :param sender: :param instance: :param kwargs: :return: None """ model_name = instance.manager.name # Get old model if exist dynamic_model = utils.get_dynamic_model(model_name) # Get field dynamic_field = instance.get_field() dynamic_field.column = instance.name # Remove field from model db utils.rm_db_field(dynamic_model, dynamic_field) # Remove field from model class dynamic_field = dynamic_model._meta.get_field(instance.name) dynamic_model._meta.local_fields.remove(dynamic_field) apps.clear_cache() utils.reregister_in_admin(dynamic_model, None)
def _clearing_dec(*args, **kwargs): from django.apps import apps try: func(*args, **kwargs) finally: # TODO: this doens't yet work. apps.clear_cache()
def test_no_sp(self): """Test loading without SP settings causes an exception.""" apps.clear_cache() with self.settings(SAML_SP=None): self.assertRaisesMessage( ImproperlyConfigured, "SAML_SP must be defined", apps.get_app_config('django_saml').ready )
def model_cleanup(self): create_models() importlib.reload(import_module(settings.ROOT_URLCONF)) app_config = apps.get_app_config("django_models_from_csv") hydrate_models_and_permissions(app_config) apps.clear_cache() clear_url_caches()
def tearDown(self): # Taken from IsolatedModelsTestCase in # django/tests/invalid_models_tests/base.py from django.apps import apps apps.app_configs['tests'].models = self._old_models apps.all_models['tests'] = self._old_models apps.clear_cache()
def test_custom_swappable_manager(self): # The models need to be removed after the test in order to prevent bad # interactions with the flush operation in other tests. _old_models = apps.app_configs['managers_regress'].models.copy() try: class SwappableModel(models.Model): stuff = models.Manager() class Meta: swappable = 'TEST_SWAPPABLE_MODEL' # Accessing the manager on a swappable model with an # explicit manager should raise an attribute error with a # helpful message msg = ( "Manager isn't available; 'managers_regress.SwappableModel' " "has been swapped for 'managers_regress.Parent'") with self.assertRaisesMessage(AttributeError, msg): SwappableModel.stuff.all() finally: apps.app_configs['managers_regress'].models = _old_models apps.all_models['managers_regress'] = _old_models apps.clear_cache()
def tearDown(self): for model in Article, Authors, Reviewers, Scientist: model._meta.managed = False apps.app_configs['model_options'].models = self._old_models apps.all_models['model_options'] = self._old_models apps.clear_cache()
def _pre_setup(self): """ Asks the management script to re-sync the database. Having test-only models is a pain. """ apps.clear_cache() call_command("loaddata", "initial_data", verbosity=0) super(DatatableViewTestCase, self)._pre_setup()
def user_model_swapped(**kwargs): if kwargs["setting"] == "AUTH_USER_MODEL": apps.clear_cache() try: from django.contrib.auth import get_user_model UserModel = get_user_model() except ImproperlyConfigured: # Some tests set an invalid AUTH_USER_MODEL. pass else: from django.contrib.auth import backends backends.UserModel = UserModel from django.contrib.auth import forms forms.UserModel = UserModel from django.contrib.auth.handlers import modwsgi modwsgi.UserModel = UserModel from django.contrib.auth.management.commands import changepassword changepassword.UserModel = UserModel from django.contrib.auth import views views.UserModel = UserModel
def test_custom_swappable_manager(self): # The models need to be removed after the test in order to prevent bad # interactions with the flush operation in other tests. _old_models = apps.app_configs['managers_regress'].models.copy() try: class SwappableModel(models.Model): stuff = models.Manager() class Meta: swappable = 'TEST_SWAPPABLE_MODEL' # Accessing the manager on a swappable model with an # explicit manager should raise an attribute error with a # helpful message msg = ( "Manager isn't available; 'managers_regress.SwappableModel' " "has been swapped for 'managers_regress.Parent'" ) with self.assertRaisesMessage(AttributeError, msg): SwappableModel.stuff.all() finally: apps.app_configs['managers_regress'].models = _old_models apps.all_models['managers_regress'] = _old_models apps.clear_cache()
def clear_app_cache(self): try: from django.apps import apps apps.clear_cache() except ImportError: from django.db.models.loading import cache cache.loaded = False
def test_explicit_swappable_manager(self): # The models need to be removed after the test in order to prevent bad # interactions with the flush operation in other tests. _old_models = apps.app_configs['managers_regress'].models.copy() try: class SwappableModel(models.Model): objects = models.Manager() class Meta: swappable = 'TEST_SWAPPABLE_MODEL' # Accessing the manager on a swappable model with an # explicit manager should raise an attribute error with a # helpful message try: SwappableModel.objects.all() self.fail('Should raise an AttributeError') except AttributeError as e: self.assertEqual( str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'" ) finally: apps.app_configs['managers_regress'].models = _old_models apps.all_models['managers_regress'] = _old_models apps.clear_cache()
def test_explicit_swappable_manager(self): # The models need to be removed after the test in order to prevent bad # interactions with the flush operation in other tests. _old_models = apps.app_configs['managers_regress'].models.copy() try: class SwappableModel(models.Model): objects = models.Manager() class Meta: swappable = 'TEST_SWAPPABLE_MODEL' # Accessing the manager on a swappable model with an # explicit manager should raise an attribute error with a # helpful message try: SwappableModel.objects.all() self.fail('Should raise an AttributeError') except AttributeError as e: self.assertEqual(str(e), "Manager isn't available; SwappableModel has been swapped for 'managers_regress.Parent'") finally: apps.app_configs['managers_regress'].models = _old_models apps.all_models['managers_regress'] = _old_models apps.clear_cache()
def test_swappable(self): # The models need to be removed after the test in order to prevent bad # interactions with the flush operation in other tests. _old_models = apps.app_configs["proxy_models"].models.copy() try: class SwappableModel(models.Model): class Meta: swappable = "TEST_SWAPPABLE_MODEL" class AlternateModel(models.Model): pass # You can't proxy a swapped model with self.assertRaises(TypeError): class ProxyModel(SwappableModel): class Meta: proxy = True finally: apps.app_configs["proxy_models"].models = _old_models apps.all_models["proxy_models"] = _old_models apps.clear_cache()
def tearDown(self): for model in Article, Authors, Reviewers, Scientist: model._meta.managed = False apps.app_configs["model_options"].models = self._old_models apps.all_models["model_options"] = self._old_models apps.clear_cache()
def user_model_swapped(**kwargs): if kwargs['setting'] == 'AUTH_USER_MODEL': from django.db.models.manager import ensure_default_manager # Reset User manager setattr(User, 'objects', User._default_manager) ensure_default_manager(User) apps.clear_cache()
def setUp(self): super().setUp() apps.clear_cache() call_command('migrate', verbosity=0, interactive=False, load_initial_data=False)
def test_no_idp(self): """Test loading without IdP settings causes an exception.""" apps.clear_cache() with self.settings(SAML_IDP=None, SAML_IDP_URL=None, SAML_IDP_FILE=None): self.assertRaisesMessage( ImproperlyConfigured, "One must be defined: SAML_IDP, SAML_IDP_URL, SAML_IDP_FILE", apps.get_app_config('django_saml').ready )
def _pre_setup(self): """ Asks the management script to re-sync the database. Having test-only models is a pain. """ apps.clear_cache() call_command('migrate', interactive=False, verbosity=0) call_command('loaddata', 'initial_data', verbosity=0) super(DatatableViewTestCase, self)._pre_setup()
def tearDown(self): # unregister InvalidStreamModel from the overall model registry # so that it doesn't break tests elsewhere for package in ('wagtailcore', 'wagtail.wagtailcore.tests'): try: del apps.all_models[package]['invalidstreammodel'] except KeyError: pass apps.clear_cache()
def tearDown(self): # unregister DeprecatedStreamModel from the overall model registry # so that it doesn't break tests elsewhere for package in ("wagtailcore", "wagtail.tests"): try: del apps.all_models[package]["deprecatedstreammodel"] except KeyError: pass apps.clear_cache()
def remove_from_app_cache(model_class, quiet=False): with apps_lock(): model_class = _pop_model_class(model_class, quiet=quiet) opts = model_class._meta for deferred_proxy in get_deferred_proxies(opts): _pop_model_class(deferred_proxy, quiet=True) unreference_model(model_class) apps.clear_cache() return model_class
def PluginInstall(self, pk): plugin = PyPlugin.objects.get(id=pk) plugin.installed = True with open('installed_apps.py', 'a+') as installed_apps_file: if installed_apps_file.write('apps.{}\n'.format(plugin.name.lower())): print('yes') else: print("no") # Como no se cargar una sola app, se leen todas las app que estan # como plugins en tiempo de ejecución al instalar cualquier app with open('%s/installed_apps.py' % settings.BASE_DIR, 'r') as ins_apps_file: for line in ins_apps_file.readlines(): settings.INSTALLED_APPS += (line.strip().rstrip('\n'), ) apps.app_configs = OrderedDict() apps.apps_ready = apps.models_ready = apps.loading = apps.ready = False apps.clear_cache() try: # Se recargan todas las aplicaciones ¿como cargar solo una? apps.populate(settings.INSTALLED_APPS) except: # plugin.installed = False print('Fallo el proceso de poblado de la app') try: # Se contruyen las migraciones del plugin call_command('makemigrations', plugin.name.lower(), interactive=False) except: # plugin.installed = False print('No hay migración de la app') try: # Se ejecutan las migraciones de la app call_command('migrate', plugin.name.lower(), interactive=False) except: # plugin.installed = False print('No se migro la app') try: # Se ejecutan las migraciones de la app call_command('loaddata', '{}.json'.format(plugin.name.lower()), interactive=False) except: # plugin.installed = False print('No se cargaron datos de la app') plugin.save() # subprocess.run[PROJECT_RELOAD] # Recargo en memoria la rutas del proyecto urlconf = settings.ROOT_URLCONF if urlconf in sys.modules: clear_url_caches() reload(sys.modules[urlconf]) return redirect(reverse('PyPlugin:list'))
def clear_cache(): """ Clear internal cache of apps loading """ if django.VERSION >= (1.7): from django.db.models import loading loading.cache.loaded = False else: from django.apps import apps apps.clear_cache()
def test_contact(self): """Test SP contact information loading.""" apps.clear_cache() with self.settings(SAML_CONTACT=None): apps.get_app_config('django_saml').ready() self.assertNotIn('contactPerson', settings.SAML_SETTINGS) apps.clear_cache() with self.settings(SAML_CONTACT={'technical': {'emailAddress': '*****@*****.**', 'givenName': 'Bob'}}): apps.get_app_config('django_saml').ready() self.assertEqual(settings.SAML_SETTINGS['contactPerson']['technical']['givenName'], 'Bob')
def test_organization(self): """Test SP organization information loading.""" apps.clear_cache() with self.settings(SAML_ORGANIZATION=None): apps.get_app_config('django_saml').ready() self.assertNotIn('organization', settings.SAML_SETTINGS) apps.clear_cache() with self.settings(SAML_ORGANIZATION={'en-US': {'name': 'thon', 'displayname': 'THON', 'url': 'thon.org'}}): apps.get_app_config('django_saml').ready() self.assertEqual(settings.SAML_SETTINGS['organization']['en-US']['displayname'], 'THON')
def setup_test_app(package, label=None): """ Setup a Django test app for the provided package to allow test-only models to be used. This function should be called from myapp.tests.__init__ like so: setup_test_app(__package__) Or, if a specific app label is required, like so: setup_test_app(__package__, 'mytests') Models defined within the package also require their app labels manually set to match, e.g.: class MyTestModel(models.Model): # ... class Meta: app_label = 'mytests' """ # # if label is None: containing_app_config = apps.get_containing_app_config(package) label = containing_app_config.label # Only suffix the app label if it has not been already. This allows # duplicate entries to be detected and prevented. It may prevent the # use of an implicit label if the tests reside in an app that # legitimately ends with "_tests", but an explicit label can always be # used. Without this check, earlier entries are returned by # get_containing_app_config() and suffixed repeatedly. if not containing_app_config.label.endswith('_tests'): label = '{}_tests'.format(containing_app_config.label) if label in apps.app_configs: # An app with this label already exists, skip adding it. This is # necessary (vs raising an exception) as there are certain conditions # that can cause this function to be run multiple times (e.g. errors # during Django's initialisation can cause this). return app_config = AppConfig.create(package) app_config.apps = apps app_config.label = label apps.app_configs[label] = app_config app_config.import_models() apps.clear_cache()
def _reset_django(settings): """ Hackish way to reset the django instance settings and AppConfig :param settings: django settings module """ if settings._wrapped != empty: clear_url_caches() from django.apps import apps apps.clear_cache() settings._wrapped = empty clear_url_caches()
def test_idp_file(self): """Test loading IdP settings from a file.""" apps.clear_cache() with self.settings( SAML_IDP=None, SAML_IDP_URL=None, SAML_IDP_FILE=os.path.join(data_directory, 'metadata.xml') ): apps.get_app_config('django_saml').ready() self.assertEqual( settings.SAML_SETTINGS['idp']['entityId'], 'http://192.168.99.100:8080/simplesaml/saml2/idp/metadata.php' )
def _reload_apps(self, force_reload: bool = False): self.is_loading = True # set flag to disable loop reloading if force_reload: # we can not use the built in functions as we need to brute force the registry apps.app_configs = OrderedDict() apps.apps_ready = apps.models_ready = apps.loading = apps.ready = False apps.clear_cache() self._try_reload(apps.populate, settings.INSTALLED_APPS) else: self._try_reload(apps.set_installed_apps, settings.INSTALLED_APPS) self.is_loading = False
def tearDown(self): apps.app_configs['migrations'].models = self._old_models apps.all_models['migrations'] = self._old_models apps.clear_cache() os.chdir(self.test_dir) try: self._rmrf(self.migration_dir) except OSError: pass os.chdir(self._cwd)
def purgeDynModel(self): """ Purges the model from Django's app registry cache. """ _model_name = 'Response_%d' % self.form.id try: # TODO: private API, please fix del apps.get_app_config(self._app_label).models[_model_name.lower()] apps.clear_cache() except KeyError: pass
def remove_from_app_cache(model_class, quiet=False): opts = model_class._meta apps = opts.apps app_label, model_name = opts.app_label, opts.model_name with apps_lock(): try: model_class = apps.app_configs[app_label].models.pop(model_name) except KeyError: if not quiet: raise ValueError("%r is not cached" % model_class) apps.clear_cache() unreference_model(model_class) return model_class
def setUp(self): from .test_app.elastic_indexes import TestSearchIndex, TestAnalyzerSearchIndex super(IndexTest, self).setUp() apps.clear_cache() call_command('migrate', verbosity=0, interactive=False, load_initial_data=False) index_builder.indexes = [ TestSearchIndex(), TestAnalyzerSearchIndex(), ] index_builder.register_signals()
def clear_cache(): """ Clear internal cache of apps loading """ import django if django.VERSION >= (1.7): try: from django.db.models import loading loading.cache.loaded = False except ImportError: # Django >= 1.9 pass else: from django.apps import apps apps.clear_cache()
def clear_table_model_cache(self): # see: http://dynamic-models.readthedocs.org/en/latest/topics/model.html#topics-model from django.conf import settings from importlib import import_module from django.core.urlresolvers import clear_url_caches from django.apps import apps app_models = apps.all_models[self.TableModel._meta.app_label] if app_models.get(self.TableModel._meta.model_name): del app_models[self.TableModel._meta.model_name] reload(import_module(settings.ROOT_URLCONF)) clear_url_caches() apps.clear_cache() self._fields = None
def tearDown(self): # Unregister the models from the overall model registry # so that it doesn't break tests elsewhere. # We can probably replace this with Django's @isolate_apps decorator. for package in ("wagtailcore", "wagtail.tests"): try: for model in ( "draftstatewithoutrevisionmodel", "draftstateincorrectrevisionmodel", "draftstatewithrevisionmodel", ): del apps.all_models[package][model] except KeyError: pass apps.clear_cache()
def app_cache_restorer(): """ A context manager that restore model cache state as it was before entering context. """ state = _app_cache_deepcopy(apps.__dict__) try: yield state finally: with apps_lock(): apps.__dict__ = state # Rebind the app registry models cache to # individual app config ones. for app_conf in apps.get_app_configs(): app_conf.models = apps.all_models[app_conf.label] apps.clear_cache()
def tearDown(self): apps.app_configs["migrations"].models = self._old_models apps.all_models["migrations"] = self._old_models apps.clear_cache() os.chdir(self.test_dir) try: self._rmrf(self.migration_dir) except OSError: pass try: self._rmrf(os.path.join(self.test_dir, "test_migrations_path_doesnt_exist")) except OSError: pass os.chdir(self._cwd)
def remove_from_app_cache(model_class, quiet=False): opts = model_class._meta apps = opts.apps with _apps_lock(): try: app_config = apps.get_app_config(opts.app_label) except ImproperlyConfigured: if quiet: return else: raise ValueError( "No cached models for app %s" % opts.app_label ) try: model = app_config.models.pop(opts.model_name) except LookupError: if quiet: return else: raise ValueError("%r is not cached" % model_class) apps.clear_cache() unreference_model(model)
def setUp(self): from .test_app.models import TestModel from .test_app.elastic_indexes import TestSearchIndex from .test_app.viewsets import TestViewSet super().setUp() apps.clear_cache() call_command('migrate', verbosity=0, interactive=False, load_initial_data=False) index_builder.indexes = [TestSearchIndex()] index_builder.register_signals() # Prepare users and groups user_model = get_user_model() self.user_1 = user_model.objects.create(username='******') self.user_2 = user_model.objects.create(username='******') group = Group.objects.create(name='group') group.user_set.add(self.user_2) tzone = get_current_timezone() # Prepare test data test_obj_1 = TestModel.objects.create(name='Object name 1', number=43, date=datetime.datetime(2018, 1, 1, 0, 0, tzinfo=tzone)) test_obj_2 = TestModel.objects.create(name='Object name 2', number=44, date=datetime.datetime(2017, 1, 1, 0, 0, tzinfo=tzone)) test_obj_3 = TestModel.objects.create(name='Object name 3', number=45, date=datetime.datetime(2016, 1, 1, 0, 0, tzinfo=tzone)) # Assing permissions assign_perm('view_testmodel', self.user_1, test_obj_1) assign_perm('view_testmodel', group, test_obj_2) assign_perm('view_testmodel', AnonymousUser(), test_obj_3) # Prepare test viewset self.test_viewset = TestViewSet.as_view(actions={ 'post': 'list_with_post', })
def user_model_swapped(**kwargs): if kwargs['setting'] == 'AUTH_USER_MODEL': apps.clear_cache() try: from django.contrib.auth import get_user_model UserModel = get_user_model() except ImproperlyConfigured: # Some tests set an invalid AUTH_USER_MODEL. pass else: from django.contrib.auth import backends backends.UserModel = UserModel from django.contrib.auth import forms forms.UserModel = UserModel from django.contrib.auth.handlers import modwsgi modwsgi.UserModel = UserModel from django.contrib.auth.management.commands import changepassword changepassword.UserModel = UserModel from django.contrib.auth import views views.UserModel = UserModel
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 test_loading_and_dumping(self): apps.clear_cache() Site.objects.all().delete() # Load fixture 1. Single JSON file, with two objects. management.call_command('loaddata', 'fixture1.json', verbosity=0) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Time to reform copyright>', '<Article: Poker has no place on ESPN>', ]) # Dump the current contents of the database as a JSON fixture self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') # Try just dumping the contents of fixtures.Category self._dumpdata_assert(['fixtures.Category'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}]') # ...and just fixtures.Article self._dumpdata_assert(['fixtures.Article'], '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') # ...and both self._dumpdata_assert(['fixtures.Category', 'fixtures.Article'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') # Specify a specific model twice self._dumpdata_assert(['fixtures.Article', 'fixtures.Article'], '[{"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') # Specify a dump that specifies Article both explicitly and implicitly self._dumpdata_assert(['fixtures.Article', 'fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') # Specify a dump that specifies Article both explicitly and implicitly, # but lists the app first (#22025). self._dumpdata_assert(['fixtures', 'fixtures.Article'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') # Same again, but specify in the reverse order self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker has no place on ESPN", "pub_date": "2006-06-16T12:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Time to reform copyright", "pub_date": "2006-06-16T13:00:00"}}]') # Specify one model from one application, and an entire other application. self._dumpdata_assert(['fixtures.Category', 'sites'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 1, "model": "sites.site", "fields": {"domain": "example.com", "name": "example.com"}}]') # Load fixture 2. JSON file imported by default. Overwrites some existing objects management.call_command('loaddata', 'fixture2.json', verbosity=0) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: Django conquers world!>', '<Article: Copyright is fine the way it is>', '<Article: Poker has no place on ESPN>', ]) # Load fixture 3, XML format. management.call_command('loaddata', 'fixture3.xml', verbosity=0) self.assertQuerysetEqual(Article.objects.all(), [ '<Article: XML identified as leading cause of cancer>', '<Article: Django conquers world!>', '<Article: Copyright is fine the way it is>', '<Article: Poker on TV is great!>', ]) # Load fixture 6, JSON file with dynamic ContentType fields. Testing ManyToOne. management.call_command('loaddata', 'fixture6.json', verbosity=0) self.assertQuerysetEqual(Tag.objects.all(), [ '<Tag: <Article: Copyright is fine the way it is> tagged "copyright">', '<Tag: <Article: Copyright is fine the way it is> tagged "law">', ], ordered=False) # Load fixture 7, XML file with dynamic ContentType fields. Testing ManyToOne. management.call_command('loaddata', 'fixture7.xml', verbosity=0) self.assertQuerysetEqual(Tag.objects.all(), [ '<Tag: <Article: Copyright is fine the way it is> tagged "copyright">', '<Tag: <Article: Copyright is fine the way it is> tagged "legal">', '<Tag: <Article: Django conquers world!> tagged "django">', '<Tag: <Article: Django conquers world!> tagged "world domination">', ], ordered=False) # Load fixture 8, JSON file with dynamic Permission fields. Testing ManyToMany. management.call_command('loaddata', 'fixture8.json', verbosity=0) self.assertQuerysetEqual(Visa.objects.all(), [ '<Visa: Django Reinhardt Can add user, Can change user, Can delete user>', '<Visa: Stephane Grappelli Can add user>', '<Visa: Prince >' ], ordered=False) # Load fixture 9, XML file with dynamic Permission fields. Testing ManyToMany. management.call_command('loaddata', 'fixture9.xml', verbosity=0) self.assertQuerysetEqual(Visa.objects.all(), [ '<Visa: Django Reinhardt Can add user, Can change user, Can delete user>', '<Visa: Stephane Grappelli Can add user, Can delete user>', '<Visa: Artist formerly known as "Prince" Can change user>' ], ordered=False) # object list is unaffected self.assertQuerysetEqual(Article.objects.all(), [ '<Article: XML identified as leading cause of cancer>', '<Article: Django conquers world!>', '<Article: Copyright is fine the way it is>', '<Article: Poker on TV is great!>', ]) # By default, you get raw keys on dumpdata self._dumpdata_assert(['fixtures.book'], '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [3, 1]}}]') # But you can get natural keys if you ask for them and they are available self._dumpdata_assert(['fixtures.book'], '[{"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]', natural_foreign_keys=True) # You can also omit the primary keys for models that we can get later with natural keys. self._dumpdata_assert(['fixtures.person'], '[{"fields": {"name": "Django Reinhardt"}, "model": "fixtures.person"}, {"fields": {"name": "Stephane Grappelli"}, "model": "fixtures.person"}, {"fields": {"name": "Artist formerly known as \\"Prince\\""}, "model": "fixtures.person"}]', natural_primary_keys=True) # Dump the current contents of the database as a JSON fixture self._dumpdata_assert(['fixtures'], '[{"pk": 1, "model": "fixtures.category", "fields": {"description": "Latest news stories", "title": "News Stories"}}, {"pk": 2, "model": "fixtures.article", "fields": {"headline": "Poker on TV is great!", "pub_date": "2006-06-16T11:00:00"}}, {"pk": 3, "model": "fixtures.article", "fields": {"headline": "Copyright is fine the way it is", "pub_date": "2006-06-16T14:00:00"}}, {"pk": 4, "model": "fixtures.article", "fields": {"headline": "Django conquers world!", "pub_date": "2006-06-16T15:00:00"}}, {"pk": 5, "model": "fixtures.article", "fields": {"headline": "XML identified as leading cause of cancer", "pub_date": "2006-06-16T16:00:00"}}, {"pk": 1, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "copyright", "tagged_id": 3}}, {"pk": 2, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "legal", "tagged_id": 3}}, {"pk": 3, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "django", "tagged_id": 4}}, {"pk": 4, "model": "fixtures.tag", "fields": {"tagged_type": ["fixtures", "article"], "name": "world domination", "tagged_id": 4}}, {"pk": 1, "model": "fixtures.person", "fields": {"name": "Django Reinhardt"}}, {"pk": 2, "model": "fixtures.person", "fields": {"name": "Stephane Grappelli"}}, {"pk": 3, "model": "fixtures.person", "fields": {"name": "Artist formerly known as \\"Prince\\""}}, {"pk": 1, "model": "fixtures.visa", "fields": {"person": ["Django Reinhardt"], "permissions": [["add_user", "auth", "user"], ["change_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, {"pk": 2, "model": "fixtures.visa", "fields": {"person": ["Stephane Grappelli"], "permissions": [["add_user", "auth", "user"], ["delete_user", "auth", "user"]]}}, {"pk": 3, "model": "fixtures.visa", "fields": {"person": ["Artist formerly known as \\"Prince\\""], "permissions": [["change_user", "auth", "user"]]}}, {"pk": 1, "model": "fixtures.book", "fields": {"name": "Music for all ages", "authors": [["Artist formerly known as \\"Prince\\""], ["Django Reinhardt"]]}}]', natural_foreign_keys=True) # Dump the current contents of the database as an XML fixture self._dumpdata_assert(['fixtures'], """<?xml version="1.0" encoding="utf-8"?> <django-objects version="1.0"><object pk="1" model="fixtures.category"><field type="CharField" name="title">News Stories</field><field type="TextField" name="description">Latest news stories</field></object><object pk="2" model="fixtures.article"><field type="CharField" name="headline">Poker on TV is great!</field><field type="DateTimeField" name="pub_date">2006-06-16T11:00:00</field></object><object pk="3" model="fixtures.article"><field type="CharField" name="headline">Copyright is fine the way it is</field><field type="DateTimeField" name="pub_date">2006-06-16T14:00:00</field></object><object pk="4" model="fixtures.article"><field type="CharField" name="headline">Django conquers world!</field><field type="DateTimeField" name="pub_date">2006-06-16T15:00:00</field></object><object pk="5" model="fixtures.article"><field type="CharField" name="headline">XML identified as leading cause of cancer</field><field type="DateTimeField" name="pub_date">2006-06-16T16:00:00</field></object><object pk="1" model="fixtures.tag"><field type="CharField" name="name">copyright</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="2" model="fixtures.tag"><field type="CharField" name="name">legal</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">3</field></object><object pk="3" model="fixtures.tag"><field type="CharField" name="name">django</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="4" model="fixtures.tag"><field type="CharField" name="name">world domination</field><field to="contenttypes.contenttype" name="tagged_type" rel="ManyToOneRel"><natural>fixtures</natural><natural>article</natural></field><field type="PositiveIntegerField" name="tagged_id">4</field></object><object pk="1" model="fixtures.person"><field type="CharField" name="name">Django Reinhardt</field></object><object pk="2" model="fixtures.person"><field type="CharField" name="name">Stephane Grappelli</field></object><object pk="3" model="fixtures.person"><field type="CharField" name="name">Artist formerly known as "Prince"</field></object><object pk="1" model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Django Reinhardt</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>add_user</natural><natural>auth</natural><natural>user</natural></object><object><natural>change_user</natural><natural>auth</natural><natural>user</natural></object><object><natural>delete_user</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="2" model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Stephane Grappelli</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>add_user</natural><natural>auth</natural><natural>user</natural></object><object><natural>delete_user</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="3" model="fixtures.visa"><field to="fixtures.person" name="person" rel="ManyToOneRel"><natural>Artist formerly known as "Prince"</natural></field><field to="auth.permission" name="permissions" rel="ManyToManyRel"><object><natural>change_user</natural><natural>auth</natural><natural>user</natural></object></field></object><object pk="1" model="fixtures.book"><field type="CharField" name="name">Music for all ages</field><field to="fixtures.person" name="authors" rel="ManyToManyRel"><object><natural>Artist formerly known as "Prince"</natural></object><object><natural>Django Reinhardt</natural></object></field></object></django-objects>""", format='xml', natural_foreign_keys=True)
def setup(verbosity, test_labels): from django.apps import apps, AppConfig 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, } # 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)) 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) installed_app_names = set(get_installed()) if module_found_in_labels and module_label not in installed_app_names: if verbosity >= 2: print("Importing application %s" % module_name) # HACK. settings.INSTALLED_APPS.append(module_label) app_config = AppConfig.create(module_label) apps.app_configs[app_config.label] = app_config app_config.import_models(apps.all_models[app_config.label]) apps.clear_cache() return state
def setUp(self): apps.clear_cache() call_command('migrate', verbosity=0, interactive=False) super().setUp()
def setUp(self): apps.clear_cache()
def tearDown(self): for model in (set(self.current_models) - self.saved_models): del self.current_models[model] apps.clear_cache()
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