def setUp(self): clear_app_resolvers() clear_url_caches() if APP_MODULE in sys.modules: del sys.modules[APP_MODULE] self.reload_urls()
def tearDown(self): clear_app_resolvers() clear_url_caches() if APP_MODULE in sys.modules: del sys.modules[APP_MODULE] self.apphook_clear()
def reload_urls(urlconf=None): clear_url_caches() if urlconf is None: urlconf = settings.ROOT_URLCONF if urlconf in sys.modules: reload(sys.modules[urlconf]) import_module(urlconf)
def admin_register(self, model, admin_site): """Register an model with admin to the test case, test client and URL reversing code.""" self.admin_site.register(model, admin_site) # Make sure the URLs are reachable by reverse() clear_url_caches() set_urlconf(tuple([path("tmp-admin/", self.admin_site.urls)]))
def reload_url_conf(): clear_url_caches() urlconf = settings.ROOT_URLCONF if urlconf in sys.modules: reload(sys.modules[urlconf]) else: import_module(urlconf)
def _django_set_urlconf(request): """Apply the @pytest.mark.urls marker, internal to pytest-django.""" marker = request.node.get_closest_marker('urls') if marker: skip_if_no_django() import django.conf try: from django.urls import clear_url_caches, set_urlconf except ImportError: # Removed in Django 2.0 from django.core.urlresolvers import clear_url_caches, set_urlconf urls = validate_urls(marker) original_urlconf = django.conf.settings.ROOT_URLCONF django.conf.settings.ROOT_URLCONF = urls clear_url_caches() set_urlconf(None) def restore(): django.conf.settings.ROOT_URLCONF = original_urlconf # Copy the pattern from # https://github.com/django/django/blob/master/django/test/signals.py#L152 clear_url_caches() set_urlconf(None) request.addfinalizer(restore)
def _post_teardown(self): """ Performs any post-test things. This includes: * Putting back the original ROOT_URLCONF if it was changed. * Rolling back the database transaction. * Restore the setUp if it was skipped. """ after_test.send(self) if hasattr(self, 'urls'): del settings.overrides['ROOT_URLCONF'] clear_url_caches() if self.should_disable_manual_transactions(): restore_transaction_methods() transaction.rollback() # transaction.leave_transaction_management() connection.close() if hasattr(self, '_skipped_setUp'): settings.setUp = self._skipped_setUp settings.tearDown = self._skipped_tearDown logging.debug('Finished test in %.2fs: %s' % (time.time() - self._start_time, self))
def _pre_setup(self): """ Performs any pre-test setup. This includes: * If the Test Case class has a 'fixtures' member, installing the named fixtures. * If the Test Case class has a 'urls' member, replace the ROOT_URLCONF with it. * Clearing the mail test outbox. * Using transactions for auto-rollback. * NOT flushing the database. * Disabling setUp for the duration of this test if it is being skipped """ enable_settings_overrides() logging.debug(f'Starting test: {self}') self._start_time = time.time() if hasattr(self, 'fixtures') and self.fixtures: # We have to use this slightly awkward syntax due to the fact # that we're using *args and **kwargs together. call_command('loaddata', *self.fixtures, **{'verbosity': 0}) if hasattr(self, 'urls'): settings.overrides['ROOT_URLCONF'] = self.urls clear_url_caches() mail.outbox = [] if self.should_disable_manual_transactions(): # transaction.enter_transaction_management() # transaction.managed(True) disable_transaction_methods() from django.contrib.sites.models import Site Site.objects.clear_cache() # fixup model_cache prefix in memcache to be make each test run idempotent # i.e. to allow row-level cache to accomodate transactional rollbacks versions = settings.CACHE_KEY_VERSIONS model_cache_version = versions.get('model_cache') if model_cache_version: versions['model_cache'] = str(time.time())[ -6:] # memcache key length limit being hit - so limit to 6 # Disable the setUp method whenever the test itself is being skipped. test_method = getattr(self, self._testMethodName) if getattr(test_method, 'SLOW_TEST', False): if env.get('SKIP_SLOW_TESTS', False): self._skipped_setUp, self.setUp = self.setUp, noop self._skipped_tearDown, self.tearDown = self.tearDown, noop # Override the default server name. self.client = Client(SERVER_NAME=self.DEFAULT_SERVER_NAME) before_test.send(self)
def reload_urlconf(urlconfs=[settings.ROOT_URLCONF]): clear_url_caches() for urlconf in urlconfs: if urlconf in sys.modules: reload(sys.modules[urlconf]) else: import_module(urlconf)
def _django_set_urlconf(request): """Apply the @pytest.mark.urls marker, internal to pytest-django.""" marker = request.node.get_closest_marker("urls") if marker: skip_if_no_django() import django.conf try: from django.urls import clear_url_caches, set_urlconf except ImportError: # Removed in Django 2.0 from django.core.urlresolvers import clear_url_caches, set_urlconf urls = validate_urls(marker) original_urlconf = django.conf.settings.ROOT_URLCONF django.conf.settings.ROOT_URLCONF = urls clear_url_caches() set_urlconf(None) def restore(): django.conf.settings.ROOT_URLCONF = original_urlconf # Copy the pattern from # https://github.com/django/django/blob/master/django/test/signals.py#L152 clear_url_caches() set_urlconf(None) request.addfinalizer(restore)
def reload_urlconf_redirects(urlconf=None): clear_url_caches() if urlconf is None: urlconf = settings.ROOT_URLCONF_REDIRECTS if urlconf in sys.modules: reload(sys.modules[urlconf]) else: import_module(urlconf)
def test_csp_report_view(self): with override_settings(DEBUG=True): urls.clear_url_caches() reload_urlconf() url = urls.reverse("csp_logger") response = self.client.post(url) self.assertEqual(response.status_code, 200)
def _reloaded_urlconfs(): """ Use this to ensure all urlconfs are reloaded as needed before the test. """ clear_url_caches() for urlconf in all_urlconfs: if urlconf in sys.modules: reload(sys.modules[urlconf])
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 setUp(self): clear_url_caches() reload(sys.modules['uw_saml.urls']) reload(sys.modules[settings.ROOT_URLCONF]) self.request = RequestFactory().post(reverse('saml_sso'), data={'SAMLResponse': ''}, HTTP_HOST='idp.uw.edu') SessionMiddleware().process_request(self.request) self.request.session.save()
def setUp(self): super(UrlsTestCase, self).setUp() reload(sys.modules[settings.ROOT_URLCONF]) import_module(settings.ROOT_URLCONF) clear_url_caches() # in case of changed the installed apps... call_command('migrate', '-v', '0')
def tearDown(self): clear_app_resolvers() clear_url_caches() if self.APP_MODULE in sys.modules: del sys.modules[self.APP_MODULE] self.reload_urls() self.apphook_clear()
def reload_urlconf(): """ Sometimes, you need to reload Django URLs, for instance if you change some settings right in your tests. """ clear_url_caches() urlconf = settings.ROOT_URLCONF if urlconf in sys.modules: importlib.reload(sys.modules[urlconf])
def admin_register(self, model, admin_site): """Register an model with admin to the test case, test client and URL reversing code.""" self.admin_site.register(model, admin_site) # Make sure the URLs are reachable by reverse() clear_url_caches() set_urlconf(tuple([ url('^tmp-admin/', self.admin_site.urls) ]))
def __call__(self, request): hostname = remove_www(request.get_host().split(":")[0]) connection.set_schema_to_public() # Checking for static tenants for schema, data in settings.TENANTS.items(): if schema in ["public", "default"]: continue if hostname in data["DOMAINS"]: tenant = SchemaDescriptor.create(schema_name=schema, domain_url=hostname) request.tenant = tenant if "URLCONF" in data: request.urlconf = data["URLCONF"] connection.set_schema(request.tenant) return self.get_response(request) # Checking for dynamic tenants else: DomainModel = get_domain_model() prefix = request.path.split("/")[1] try: domain = DomainModel.objects.select_related("tenant").get( domain=hostname, folder=prefix) except DomainModel.DoesNotExist: try: domain = DomainModel.objects.select_related("tenant").get( domain=hostname, folder="") except DomainModel.DoesNotExist: raise self.TENANT_NOT_FOUND_EXCEPTION( "No tenant for hostname '%s'" % hostname) tenant = domain.tenant tenant.domain_url = hostname request.urlconf = settings.TENANTS["default"]["URLCONF"] request.strip_tenant_from_path = lambda x: x if prefix and domain.folder == prefix: dynamic_path = settings.TENANTS["default"][ "URLCONF"] + "._automatically_prefixed" if not sys.modules.get(dynamic_path): spec = find_spec(settings.TENANTS["default"]["URLCONF"]) prefixed_url_module = module_from_spec(spec) spec.loader.exec_module(prefixed_url_module) prefixed_url_module.urlpatterns = tenant_patterns( *import_string(settings.TENANTS["default"]["URLCONF"] + ".urlpatterns")) sys.modules[dynamic_path] = prefixed_url_module del spec tenant.path_prefix = prefix request.urlconf = dynamic_path request.strip_tenant_from_path = lambda x: re.sub( r"^/{}/".format(prefix), "/", x) clear_url_caches( ) # Required to remove previous tenant prefix from cache request.tenant = tenant connection.set_schema(request.tenant) return self.get_response(request)
def override_urlconf(): has_old = hasattr(settings, 'ROOT_URLCONF') old = getattr(settings, 'ROOT_URLCONF', None) settings.ROOT_URLCONF = 'statictemplate.management.commands.statictemplate' clear_url_caches() yield if has_old: setattr(settings, 'ROOT_URLCONF', old) else: # NOQA delattr(settings, 'ROOT_URLCONF')
def reload_urlconf(): """ Reloads Django's urlpatterns definition. """ clear_url_caches() urlconf = settings.ROOT_URLCONF if urlconf in sys.modules: reload(sys.modules[urlconf]) else: import_module(urlconf)
def _reload_urlconf(): """ Reload Django URL configuration and clean caches """ module = importlib.import_module(settings.ROOT_URLCONF) if six.PY2: reload(module) else: importlib.reload(module) clear_url_caches()
def reset_urlconf(self): url_conf = getattr(settings, 'ROOT_URLCONF', False) if url_conf: try: reload(import_module(url_conf)) except: pass reload(import_module('pages.urls')) reload(import_module('pages.testproj.urls')) clear_url_caches()
def reload_urlconf(urlconf=None): if urlconf is None: from django.conf import settings urlconf = settings.ROOT_URLCONF if urlconf in sys.modules: from django.urls import clear_url_caches reload(sys.modules[urlconf]) clear_url_caches()
def add_test_view(self, test_object=None): urlconf = importlib.import_module(settings.ROOT_URLCONF) urlconf.urlpatterns.insert( 0, url(regex=self.test_view_url, view=self._test_view_factory(test_object=test_object), name=self.test_view_name)) clear_url_caches() self.has_test_view = True
def _reload_urls(self): """Clears out the URL caches, and reloads the root urls module. It re-triggers the autodiscovery mechanism for Horizon. Allows URLs to be re-calculated after registering new dashboards. Useful only for testing and should never be used on a live site. """ urls.clear_url_caches() moves.reload_module(import_module(settings.ROOT_URLCONF)) base.Horizon._urls()
def reload_urlconf(): """ Enforce URL configuration reload. Required when using override_settings for a setting present in `marsha.urls`. """ if settings.ROOT_URLCONF in sys.modules: # The module is already loaded, need to reload reload(sys.modules[settings.ROOT_URLCONF]) clear_url_caches()
def reload_urlconf(): """ reloads the urlconfs after settings variables are updated """ urlconf = settings.ROOT_URLCONF acc_urls = "accounts.urls" if urlconf in sys.modules and acc_urls in sys.modules: clear_url_caches() reload(sys.modules[urlconf]) reload(sys.modules[acc_urls])
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 process_request(self, request): # Short circuit if tenant is already set by another middleware. # This allows for multiple tenant-resolving middleware chained together. if hasattr(request, "tenant"): return connection.set_schema_to_public() tenant = None urlconf = None TenantModel = get_tenant_model() hostname = self.hostname_from_request(request) subfolder_prefix_path = "/{}/".format(get_subfolder_prefix()) # We are in the public tenant if not request.path.startswith(subfolder_prefix_path): try: tenant = TenantModel.objects.get( schema_name=get_public_schema_name()) except TenantModel.DoesNotExist: raise self.TENANT_NOT_FOUND_EXCEPTION( "Unable to find public tenant") # Do we have a public-specific urlconf? if (hasattr(settings, "PUBLIC_SCHEMA_URLCONF") and tenant.schema_name == get_public_schema_name()): urlconf = settings.PUBLIC_SCHEMA_URLCONF # We are in a specific tenant else: path_chunks = request.path[len(subfolder_prefix_path):].split("/") tenant_subfolder = path_chunks[0] try: tenant = TenantModel.objects.get( domains__domain=tenant_subfolder) except TenantModel.DoesNotExist: raise self.TENANT_NOT_FOUND_EXCEPTION( 'No tenant for subfolder "%s"' % (tenant_subfolder or "")) tenant.domain_subfolder = tenant_subfolder urlconf = get_subfolder_urlconf(tenant) tenant.domain_url = hostname request.tenant = tenant connection.set_tenant(request.tenant) clear_url_caches( ) # Required to remove previous tenant prefix from cache, if present if urlconf: request.urlconf = urlconf set_urlconf(urlconf)
def setUp(self): # Explicitly clear the cache of site root paths. Normally this would be kept # in sync by the Site.save logic, but this is bypassed when the database is # rolled back between tests using transactions. from django.core.cache import cache cache.delete('wagtail_site_root_paths') # also need to clear urlresolver caches before/after tests, because we override # ROOT_URLCONF in some tests here from django.urls import clear_url_caches clear_url_caches()
def reload_urlconf(urlconf=None): """Reload urlconf, this should be used when some urlpatterns are included according to settings """ clear_url_caches() if urlconf is None: urlconf = settings.ROOT_URLCONF if urlconf in sys.modules: reload(sys.modules[urlconf]) else: import_module(urlconf)
def setUp(self): # useful to make sure the tests will be properly # executed in an exotic project. self.set_setting('PAGE_TEMPLATES', test_settings.PAGE_TEMPLATES) self.set_setting('PAGE_DEFAULT_TEMPLATE', test_settings.PAGE_DEFAULT_TEMPLATE) self.old_url_conf = getattr(settings, 'ROOT_URLCONF') setattr(settings, 'ROOT_URLCONF', 'pages.testproj.urls') clear_url_caches() cache.clear()
def reload_urls(settings, urlconf=None, cms_apps=True): if 'cms.urls' in sys.modules: reload_module(sys.modules['cms.urls']) if urlconf is None: urlconf = settings.ROOT_URLCONF if urlconf in sys.modules: reload_module(sys.modules[urlconf]) clear_url_caches() if cms_apps: from cms.appresolver import clear_app_resolvers, get_app_patterns clear_app_resolvers() get_app_patterns()
def add_test_view(self, test_object): urlconf = importlib.import_module(settings.ROOT_URLCONF) def test_view(request): template = Template('{{ object }}') context = Context( {'object': test_object, 'resolved_object': test_object} ) return HttpResponse(template.render(context=context)) urlconf.urlpatterns.insert(0, url(TEST_VIEW_URL, test_view, name=TEST_VIEW_NAME)) clear_url_caches() self.has_test_view = True
def add_test_view(self, test_object): from mayan.urls import urlpatterns def test_view(request): template = Template('{{ object }}') context = Context( {'object': test_object, 'resolved_object': test_object} ) return HttpResponse(template.render(context=context)) urlpatterns.insert(0, url(TEST_VIEW_URL, test_view, name=TEST_VIEW_NAME)) clear_url_caches() self.has_test_view = True
def reload_urls(self): url_modules = [ 'cms.urls', 'test_addon.urls', settings.ROOT_URLCONF, ] clear_app_resolvers() clear_url_caches() for module in url_modules: if module in sys.modules: del sys.modules[module]
def reset_urls(self, urlconf_modules=None): """Reset `urls.py` for a set of Django apps.""" if urlconf_modules is None: urlconf_modules = [settings.ROOT_URLCONF] if self.URLCONF_MODULES is not None: urlconf_modules.extend(self.URLCONF_MODULES) for urlconf in urlconf_modules: if urlconf in sys.modules: reload(sys.modules[urlconf]) clear_url_caches() # Resolve a URL so that the new urlconf gets loaded resolve('/')
def reload_urls(self): from django.conf import settings url_modules = [ 'cms.urls', self.APP_MODULE, settings.ROOT_URLCONF, ] clear_app_resolvers() clear_url_caches() for module in url_modules: if module in sys.modules: del sys.modules[module]
def test_all_urls_accounted_for(self): """ Ensure all URLs that have not been explicitly excluded are present in self.covered_urls. """ clear_url_caches() seen_patterns = set() patterns = get_urlpatterns() original_resolve = URLPattern.resolve def resolve_and_make_note(self, url, *args, **kwargs): match = original_resolve(self, url, *args, **kwargs) if match: seen_patterns.add(self) return match with patch(RESOLVE_PATH, resolve_and_make_note): for url in list(self.covered_urls) + list(self.uncovered_urls): resolve(url.split('?')[0]) all_patterns = extract_all_patterns_from_urlpatterns( patterns, self.uncovered_includes) not_accounted_for = [p for p in all_patterns if p[1] not in seen_patterns] if not_accounted_for: raise self.failureException( 'The following views are untested:\n\n{0}\n\n{1}'.format( '\n'.join([ '{base} {route} ({name})'.format( base=base, name=pattern.name, route=( getattr(pattern.pattern, '_route', None) or getattr(pattern.pattern, '_regex', '-') if django.VERSION >= (2, 0) else pattern._regex ), ) for base, pattern in not_accounted_for ]), IGNORE_TUTORIAL.format(name=self.__class__.__name__), ) )
def reload_urls(self): """ Clean up url related things (caches, app resolvers, modules). Taken from cms. :return: None """ clear_app_resolvers() clear_url_caches() url_modules = [ 'cms.urls', 'aldryn_events.urls', settings.ROOT_URLCONF ] for module in url_modules: if module in sys.modules: del sys.modules[module]
def reload_urlconf(urlconf=None): from imp import reload # python 3 needs this import. if urlconf is None: from django.conf import settings urlconf = settings.ROOT_URLCONF if HELPDESK_URLCONF in sys.modules: reload(sys.modules[HELPDESK_URLCONF]) if urlconf in sys.modules: reload(sys.modules[urlconf]) from django.urls import clear_url_caches clear_url_caches()
def setUp(self): self.APP_MODULE = 'aldryn_forms.cms_apps.FormsApp' clear_app_resolvers() clear_url_caches() if self.APP_MODULE in sys.modules: del sys.modules[self.APP_MODULE] self.page = create_page( 'tpage', 'test_page.html', 'en', published=True, apphook='FormsApp', ) try: self.placeholder = self.page.placeholders.get(slot='content') except AttributeError: self.placeholder = self.page.get_placeholders('en').get(slot='content') self.redirect_url = 'http://www.google.com' plugin_data = { 'redirect_type': 'redirect_to_url', 'url': self.redirect_url, } self.form_plugin = add_plugin(self.placeholder, 'FormPlugin', 'en', **plugin_data) # noqa: E501 add_plugin( self.placeholder, 'SubmitButton', 'en', target=self.form_plugin, label='Submit', ) self.form_plugin.action_backend = 'default' self.form_plugin.save() if CMS_3_6: self.page.publish('en') self.reload_urls() self.apphook_clear()
def reload_urls(self, apphook_object=None): """ Clean up url related things (caches, app resolvers, modules). Taken from cms. :return: None """ if apphook_object is None: apphook_object = self.get_apphook_object() app_module = apphook_object.__module__ package = app_module.split('.')[0] clear_app_resolvers() clear_url_caches() url_modules = [ 'cms.urls', '{0}.urls'.format(package), settings.ROOT_URLCONF ] for module in url_modules: if module in sys.modules: del sys.modules[module]
def reload_urlconf(urlconf=None): from django.utils import six if six.PY2: from imp import reload else: from importlib import reload if urlconf is None: from django.conf import settings urlconf = settings.ROOT_URLCONF if HELPDESK_URLCONF in sys.modules: reload(sys.modules[HELPDESK_URLCONF]) if urlconf in sys.modules: reload(sys.modules[urlconf]) from django.urls import clear_url_caches clear_url_caches()
def reload_url_conf(): # Reload URLs to pick up the overridden settings if settings.ROOT_URLCONF in sys.modules: reload(sys.modules[settings.ROOT_URLCONF]) import_module(settings.ROOT_URLCONF) clear_url_caches()
def tearDown(self): # Make sure we will leave an empty cache for other testcases. clear_url_caches()
def setUp(self): # Make sure the cache is empty before we are doing our tests. clear_url_caches()
def tearDown(self): clear_url_caches() set_urlconf(None)
def root_urlconf_changed(**kwargs): if kwargs['setting'] == 'ROOT_URLCONF': from django.urls import clear_url_caches, set_urlconf clear_url_caches() set_urlconf(None)
def tearDownClass(cls): super(AdminTestCase, cls).tearDownClass() clear_url_caches() set_urlconf(None)
def _clear_urlconf(): clear_url_caches() set_urlconf(None)
def restore(): django.conf.settings.ROOT_URLCONF = original_urlconf # Copy the pattern from # https://github.com/django/django/blob/master/django/test/signals.py#L152 clear_url_caches() set_urlconf(None)
def reloadUrls(self): reload(import_module(settings.ROOT_URLCONF)) clear_url_caches()