def test_startview_mixin_with_create_view(self): class StartView(views.StartFlowMixin, generic.CreateView): model = StartViewFlowEntity fields = [] view = StartView.as_view() user = User.objects.create(username='******', is_superuser=True) # get request = RequestFactory().get('/start/') request.user = user request.resolver_match = resolve('/test/start/') response = view(request, flow_class=StartViewTestFlow, flow_task=StartViewTestFlow.start) self.assertEqual(response.template_name, ('tests/test_views_start/startviewtest/start.html', 'tests/test_views_start/startviewtest/start.html', 'viewflow/flow/start.html')) # post request = RequestFactory().post('/start/') request.user = user request.resolver_match = resolve('/test/start/') response = view(request, flow_class=StartViewTestFlow, flow_task=StartViewTestFlow.start) self.assertEqual(response.status_code, 302) process = StartViewTestFlow.process_class.objects.all()[0] process.get_task(StartViewTestFlow.start, status=[STATUS.DONE])
def post_fork(server, worker): import mimetypes mimetypes.init() # hacky way to address gunicorn gevent requests hitting django too early before urls are loaded # see: https://github.com/benoitc/gunicorn/issues/527#issuecomment-19601046 from django.urls import resolve resolve('/')
def test_flowview(self): view = views.UpdateProcessView.as_view() user = User.objects.create(username='******', is_superuser=True) act = TaskViewTestFlow.start.run() task = act.process.get_task(TaskViewTestFlow.task) # assigned get act = task.activate() act.assign(user=user) request = RequestFactory().get('/start/') request.user = user request.resolver_match = resolve('/test/1/task/1/') response = view(request, flow_class=TaskViewTestFlow, flow_task=TaskViewTestFlow.task, process_pk=act.process.pk, task_pk=task.pk) self.assertEqual(response.status_code, 200) self.assertEqual(response.template_name, ('tests/test_views_task/taskviewtest/task.html', 'tests/test_views_task/taskviewtest/task.html', 'viewflow/flow/task.html')) # assigned post request = RequestFactory().post('/task/') request.user = user request.resolver_match = resolve('/test/1/task/1/') response = view(request, flow_class=TaskViewTestFlow, flow_task=TaskViewTestFlow.task, process_pk=act.process.pk, task_pk=task.pk) self.assertEqual(response.status_code, 302) task.refresh_from_db() self.assertEqual(task.status, STATUS.DONE)
def create_new_url(url): match_kamerstuk = re.match("kst-(\d+)-(\d+)", url) match_dossier = re.match("/dossier/(\d+)", url) new_url = '' if match_kamerstuk: dossier_id = match_kamerstuk.group(1) sub_id = match_kamerstuk.group(2) kamerstukken = Kamerstuk.objects.filter(id_main=dossier_id, id_sub=sub_id) if kamerstukken.exists(): new_url = reverse('kamerstuk', args=(dossier_id, sub_id,)) elif match_dossier: dossier_id = match_dossier.group(1) if Dossier.objects.filter(dossier_id=dossier_id).exists(): new_url = reverse('dossier-timeline', args=(dossier_id,)) if not new_url: try: resolve(url) openkamer_url = True except Resolver404: openkamer_url = False if openkamer_url or url[0] == '#' or 'http' in url: # openkamer, anchor or external url new_url = url else: if url[0] != '/': url = '/' + url new_url = 'https://zoek.officielebekendmakingen.nl' + url return new_url
def get_resolver_matches_chain(request, data=None): """Walk the current request URL path up to the top, attempting to resolve along the way """ from django.urls import Resolver404 from django.urls import resolve resolver_matches_chain = [] path = request.path resolver_matches_chain.append((path, request.resolver_match,)) while path: try: path = path[:path.rindex('/')] resolver_match = resolve(path) resolver_matches_chain.append((path, resolver_match)) except Resolver404: # could not resolve without '/' path_with_slash = path + '/' if request.path != path_with_slash: try: resolver_match = resolve(path_with_slash) resolver_matches_chain.append((path_with_slash, resolver_match)) except Resolver404: pass except ValueError: # '/' substring not found break return resolver_matches_chain
def test_urls(self): # This executes the code at the module level url = reverse('app_library') resolver = resolve(url) self.assertEqual('/apps/', url) self.assertEqual('library', resolver.func.__name__) self.assertEqual('tethys_apps.views', resolver.func.__module__) url = reverse('send_beta_feedback') resolver = resolve(url) self.assertEqual('/apps/send-beta-feedback/', url) self.assertEquals('send_beta_feedback_email', resolver.func.__name__) self.assertEqual('tethys_apps.views', resolver.func.__module__) url = reverse('test_app:home') resolver = resolve(url) self.assertEqual('/apps/test-app/', url) self.assertEquals('home', resolver.func.__name__) self.assertEqual('tethys_apps.tethysapp.test_app.controllers', resolver.func.__module__) url = reverse('test_extension:home', kwargs={'var1': 'foo', 'var2': 'bar'}) resolver = resolve(url) self.assertEqual('/extensions/test-extension/foo/bar/', url) self.assertEquals('home', resolver.func.__name__) self.assertEqual('tethysext.test_extension.controllers', resolver.func.__module__) url = reverse('test_extension:home', args=['foo', 'bar']) resolver = resolve(url) self.assertEqual('/extensions/test-extension/foo/bar/', url) self.assertEquals('home', resolver.func.__name__) self.assertEqual('tethysext.test_extension.controllers', resolver.func.__module__)
def test_task_cancel_view(self): act = ActionsTestFlow.start.run() view = views.CancelTaskView.as_view() task = act.process.get_task(ActionsTestFlow.task, status=[STATUS.NEW]) # get request = RequestFactory().get('/cancel/') request.user = User(username='******', is_superuser=True) request.resolver_match = resolve('/test/') response = view( request, flow_class=ActionsTestFlow, flow_task=ActionsTestFlow.task, process_pk=act.process.pk, task_pk=task.pk) self.assertEqual(response.status_code, 200) self.assertEqual(response.template_name, ('tests/test_views_actions/actionstest/task_cancel.html', 'tests/test_views_actions/actionstest/task_cancel.html', 'viewflow/flow/task_cancel.html', 'viewflow/flow/task_action.html')) self.assertEqual(response.context_data['activation'].process, act.process) # post request = RequestFactory().post('/cancel/', {'run_action': 1}) request.user = User(username='******', is_superuser=True) request.resolver_match = resolve('/test/') response = view( request, flow_class=ActionsTestFlow, flow_task=ActionsTestFlow.start, process_pk=act.process.pk, task_pk=task.pk) task.refresh_from_db() self.assertEqual(response.status_code, 302) self.assertEqual(task.status, STATUS.CANCELED) self.assertIsNotNone(task.finished)
def test_process_cancel_view(self): act = ActionsTestFlow.start.run() view = views.CancelProcessView.as_view() # get request = RequestFactory().get('/cancel/') request.user = User(username='******', is_superuser=True) request.resolver_match = resolve('/test/') response = view(request, flow_class=ActionsTestFlow, process_pk=act.process.pk) self.assertEqual(response.status_code, 200) self.assertEqual(response.template_name, ('tests/test_views_actions/actionstest/process_cancel.html', 'viewflow/flow/process_cancel.html')) self.assertEqual(response.context_data['process'], act.process) self.assertEqual(len(response.context_data['active_tasks']), 1) self.assertEqual(response.context_data['uncancelable_tasks'], []) # post request = RequestFactory().post('/cancel/', {'_cancel_process': 1}) request.user = User(username='******', is_superuser=True) request.resolver_match = resolve('/test/') response = view(request, flow_class=ActionsTestFlow, process_pk=act.process.pk) act.process.refresh_from_db() self.assertEqual(response.status_code, 302) self.assertEqual(act.process.status, STATUS.CANCELED) canceled_task = act.process.get_task(ActionsTestFlow.task, status=[STATUS.CANCELED]) self.assertIsNotNone(canceled_task.finished)
def internal_path_exists(path): """ Validates that url path is registered and can properly be resolved in a django configuration. """ try: resolve(path) except Http404: raise ValidationError("'{0}' is not a valid url.".format(path))
def test_apis_url_exist(self): try: # PostList resolve('/api/post/') # PostDetail resolve('/api/post/1/') except NoReverseMatch as e: self.fail(e)
def test_invalid_resolve(self): test_urls = [ '/lookahead-/not-a-city/', '/lookbehind-/not-a-city/', '/lookahead+/other-city/', '/lookbehind+/other-city/', ] for test_url in test_urls: with self.assertRaises(Resolver404): resolve(test_url)
def _get_return_path_from_post(request): return_path = request.POST.get('return_path') try: if not return_path: raise ValueError() if not return_path.startswith('/'): raise ValueError() resolve(return_path) return return_path except (Http404, ValueError): return None
def is_valid_path(path, urlconf=None): """ Return True if the given path resolves against the default URL resolver, False otherwise. This is a convenience method to make working with "is this a match?" cases easier, avoiding try...except blocks. """ try: resolve(path, urlconf) return True except Resolver404: return False
def test_get_next_task_url_back(self): request = RequestFactory().get('/test/', {'back': '/test_back_url/'}) request.user = User(username='******') request.resolver_match = resolve('/test/') next_url = views.get_next_task_url(request, None) self.assertEqual(next_url, '/test_back_url/') request = RequestFactory().get('/test/', {'back': 'http://unsafe.com/test_back_url/'}) request.user = User(username='******') request.resolver_match = resolve('/test/') next_url = views.get_next_task_url(request, None) self.assertEqual(next_url, '/')
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 test_admin_timeline_prunes_user_output(self): """multiple users in timeline is confusing.""" admin = self.User.objects.create(username="******", email="*****@*****.**") admin.is_staff = True admin.is_superuser = True admin.save() # create a drip campaign that will surely give us duplicates. model_drip = Drip.objects.create( name="A Custom Week Ago", subject_template="HELLO {{ user.username }}", body_html_template="KETTEHS ROCK!" ) QuerySetRule.objects.create( drip=model_drip, field_name="date_joined", lookup_type="gte", field_value=(timezone.now() - timedelta(days=1)).isoformat(), ) # then get it's admin view. rf = RequestFactory() timeline_url = reverse( "admin:drip_timeline", kwargs={"drip_id": model_drip.id, "into_past": 3, "into_future": 3} ) request = rf.get(timeline_url) request.user = admin match = resolve(timeline_url) response = match.func(request, *match.args, **match.kwargs) # check that our admin (not excluded from test) is shown once. self.assertEqual(unicode(response.content).count(admin.email), 1)
def test_developer_urls_services(self): url = reverse('services:wps_home') resolver = resolve(url) self.assertEqual('/developer/services/wps/', url) self.assertEqual('wps_home', resolver.func.__name__) self.assertEqual('tethys_services.views', resolver.func.__module__) self.assertEqual('services', resolver.namespaces[0])
def add_section(self, name, url, icon, action="formax", button="Save", nobutton=False, dependents=None): resolver = resolve(url) self.request.META["HTTP_X_FORMAX"] = 1 self.request.META["HTTP_X_PJAX"] = 1 start = time.time() open = self.request.GET.get("open", None) if open == name: # pragma: needs cover action = "open" response = resolver.func(self.request, *resolver.args, **resolver.kwargs) # redirects don't do us any good if not isinstance(response, HttpResponseRedirect): self.sections.append( dict( name=name, url=url, response=response.rendered_content, icon=icon, action=action, button=button, nobutton=nobutton, dependents=dependents, ) ) if settings.DEBUG: print("%s took: %f" % (url, time.time() - start))
def test_user_urls_profile(self): url = reverse('user:profile', kwargs={'username': '******'}) resolver = resolve(url) self.assertEqual('/user/foo/', url) self.assertEqual('profile', resolver.func.__name__) self.assertEqual('tethys_portal.views.user', resolver.func.__module__)
def test_developer_urls_gizmos(self): url = reverse('gizmos:showcase') resolver = resolve(url) self.assertEqual('/developer/gizmos/', url) self.assertEqual('index', resolver.func.__name__) self.assertEqual('tethys_gizmos.views.gizmo_showcase', resolver.func.__module__) self.assertEqual('gizmos', resolver.namespaces[0])
def test_converter_resolve(self): for url, (url_name, app_name, kwargs) in converter_test_data: with self.subTest(url=url): match = resolve(url) self.assertEqual(match.url_name, url_name) self.assertEqual(match.app_name, app_name) self.assertEqual(match.kwargs, kwargs)
def generate_stats(self, request, response): self.record_stats({ 'get': [(k, request.GET.getlist(k)) for k in sorted(request.GET)], 'post': [(k, request.POST.getlist(k)) for k in sorted(request.POST)], 'cookies': [(k, request.COOKIES.get(k)) for k in sorted(request.COOKIES)], }) view_info = { 'view_func': _("<no view>"), 'view_args': 'None', 'view_kwargs': 'None', 'view_urlname': 'None', } try: match = resolve(request.path) func, args, kwargs = match view_info['view_func'] = get_name_from_obj(func) view_info['view_args'] = args view_info['view_kwargs'] = kwargs view_info['view_urlname'] = getattr(match, 'url_name', _("<unavailable>")) except Http404: pass self.record_stats(view_info) if hasattr(request, 'session'): self.record_stats({ 'session': [(k, request.session.get(k)) for k in sorted(request.session.keys(), key=force_text)] })
def add_preserved_filters(context, url, popup=False, to_field=None): opts = context.get('opts') preserved_filters = context.get('preserved_filters') parsed_url = list(urlparse(url)) parsed_qs = dict(parse_qsl(parsed_url[4])) merged_qs = {} if opts and preserved_filters: preserved_filters = dict(parse_qsl(preserved_filters)) match_url = '/%s' % url.partition(get_script_prefix())[2] try: match = resolve(match_url) except Resolver404: pass else: current_url = '%s:%s' % (match.app_name, match.url_name) changelist_url = 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name) if changelist_url == current_url and '_changelist_filters' in preserved_filters: preserved_filters = dict(parse_qsl(preserved_filters['_changelist_filters'])) merged_qs.update(preserved_filters) if popup: from django.contrib.admin.options import IS_POPUP_VAR merged_qs[IS_POPUP_VAR] = 1 if to_field: from django.contrib.admin.options import TO_FIELD_VAR merged_qs[TO_FIELD_VAR] = to_field merged_qs.update(parsed_qs) parsed_url[4] = urlencode(merged_qs) return urlunparse(parsed_url)
def dispatch(self, request, *args, **kwargs): # Set up since we need to super() later instead of earlier. self.request = request self.args = args self.kwargs = kwargs # Get the current object, url slug, and # urlpattern name (namespace aware). obj = self.get_object() slug = self.kwargs.get(self.slug_url_kwarg, None) match = resolve(request.path_info) url_parts = match.namespaces url_parts.append(match.url_name) current_urlpattern = ":".join(url_parts) # Figure out what the slug is supposed to be. if hasattr(obj, "get_canonical_slug"): canonical_slug = obj.get_canonical_slug() else: canonical_slug = self.get_canonical_slug() # If there's a discrepancy between the slug in the url and the # canonical slug, redirect to the canonical slug. if canonical_slug != slug: params = {self.pk_url_kwarg: obj.pk, self.slug_url_kwarg: canonical_slug, 'permanent': True} return redirect(current_urlpattern, **params) return super(CanonicalSlugDetailMixin, self).dispatch( request, *args, **kwargs)
def test_url_namespace02(self): request = self.request_factory.get('/') request.resolver_match = resolve('/ns2/') template = self.engine.get_template('url-namespace02') context = RequestContext(request) output = template.render(context) self.assertEqual(output, '/ns2/named-client/42/')
def server_error(request, template_name='500.html'): """ 500 error handler. """ urlname = resolve(request.path).url_name submission_urls = [ 'receiver_secure_post', 'receiver_secure_post_with_app_id', 'receiver_post_with_app_id' ] if urlname in submission_urls + ['app_aware_restore']: return HttpResponse(status=500) domain = get_domain_from_url(request.path) or '' # hat tip: http://www.arthurkoziel.com/2009/01/15/passing-mediaurl-djangos-500-error-view/ t = loader.get_template(template_name) type, exc, tb = sys.exc_info() traceback_text = format_traceback_the_way_python_does(type, exc, tb) traceback_key = uuid.uuid4().hex cache.cache.set(traceback_key, traceback_text, 60*60) return HttpResponseServerError(t.render( context={ 'MEDIA_URL': settings.MEDIA_URL, 'STATIC_URL': settings.STATIC_URL, 'domain': domain, '500traceback': traceback_key, }, request=request, ))
def reset_cached_api(request, apiurl): """ This admin call gets the url of the original api that we wish to reset, backwards resolves that original function and gets its data back into cache :param request: :param apiurl: :return: """ from undecorated import undecorated # from importlib import import_module try: match = resolve("/api/{}".format(apiurl)) #mod = import_module(".".join(match.view_name.split(".")[:-1])) Dont actually need this, resolve gets us the func itself #func = mod.__getattribute__(match.func.func_name) if "django_cache" in match.func.func_dict: api_view = undecorated(match.func) redecorated_api_view = scache.django_cache(action="reset")(api_view) redecorated_api_view(request, *match.args, **match.kwargs) return HttpResponseRedirect("/api/{}".format(apiurl)) else: raise Http404("API not in cache") except Resolver404 as re: logger.warn("Attempted to reset invalid url") raise Http404() except Exception as e: logger.warn("Unable to reset cache for {}".format(apiurl)) raise Http404()
def get_via_uri(self, uri, request=None): """ This pulls apart the salient bits of the URI and populates the resource via a ``obj_get``. Optionally accepts a ``request``. If you need custom behavior based on other portions of the URI, simply override this method. """ prefix = get_script_prefix() chomped_uri = uri if prefix and chomped_uri.startswith(prefix): chomped_uri = chomped_uri[len(prefix) - 1:] try: view, args, kwargs = resolve(chomped_uri) resource_name = kwargs['resource_name'] resource_class = self.resource_mapping[resource_name] except (Resolver404, KeyError): raise NotFound("The URL provided '%s' was not a link to a valid resource." % uri) parent_resource = resource_class(api_name=self._meta.api_name) kwargs = parent_resource.remove_api_resource_names(kwargs) bundle = Bundle(request=request) return parent_resource.obj_get(bundle, **kwargs)
def forced_auth_req(self, method, url, user=None, data=None, request_format='json', **kwargs): """ Function that allows api methods to be called with forced authentication If `user` parameter not provided, then `self.user` will be used If `view` parameter is provided, then the `view` function will be called directly, otherwise `url` will be resolved """ factory = APIRequestFactory() data = data or {} req_to_call = getattr(factory, method) request = req_to_call(url, data, format=request_format, **kwargs) user = user or self.user force_authenticate(request, user=user) if "view" in kwargs: view = kwargs.pop("view") response = view(request) else: view_info = resolve(url) view = view_info.func response = view(request, *view_info.args, **view_info.kwargs) if hasattr(response, 'render'): response.render() return response
def test_matching_urls(self): def no_converter(x): return x test_data = ( ('int', {'0', '1', '01', 1234567890}, int), ('str', {'abcxyz'}, no_converter), ('path', {'allows.ANY*characters'}, no_converter), ('slug', {'abcxyz-ABCXYZ_01234567890'}, no_converter), ('uuid', {'39da9369-838e-4750-91a5-f7805cd82839'}, uuid.UUID), ) for url_name, url_suffixes, converter in test_data: for url_suffix in url_suffixes: url = '/%s/%s/' % (url_name, url_suffix) with self.subTest(url=url): match = resolve(url) self.assertEqual(match.url_name, url_name) self.assertEqual(match.kwargs, {url_name: converter(url_suffix)}) # reverse() works with string parameters. string_kwargs = {url_name: url_suffix} self.assertEqual(reverse(url_name, kwargs=string_kwargs), url) # reverse() also works with native types (int, UUID, etc.). if converter is not no_converter: # The converted value might be different for int (a # leading zero is lost in the conversion). converted_value = match.kwargs[url_name] converted_url = '/%s/%s/' % (url_name, converted_value) self.assertEqual(reverse(url_name, kwargs={url_name: converted_value}), converted_url)
def test_admin_home_procedures_is_resolved(self): url = reverse('systemadministrator_procedures') self.assertEquals(resolve(url).func.view_class, ProcedureView)
def test_login_urls_is_resolved(self): url = reverse('login') self.assertEquals(resolve(url).func, user_login)
def test_view_function(self): view = resolve('/reset/{uidb64}/{token}/'.format(uidb64=self.uid, token=self.token)) self.assertEquals(view.func.view_class, auth_views.PasswordResetConfirmView)
def test_aboutpage_url_resolves_aboutpageview(self): view = resolve('/about') self.assertEqual(view.func.__name__, AboutPageView.as_view().__name__)
def test_view_function(self): view = resolve('/reset/done/') self.assertEquals(view.func.view_class, auth_views.PasswordResetDoneView)
def test_signup_url_resolves_signup_view(self): view = resolve('/signup/') self.assertEquals(view.func, signup)
def test_homepage_url_resolves_homepageview(self): view = resolve('/') self.assertEqual(view.func.__name__, HomePageView.as_view().__name__)
def test_resolve_root_url_to_home_page(self): found = resolve('/') self.assertEqual(found.func, home_page)
def test_new_topic_url_resolves_new_topic_view(self): view = resolve('/boards/1/new/') self.assertEquals(view.func, new_topic)
def test_url_for_homepageview_using_viewname(self): url = reverse('home') assert resolve(url).view_name == 'home'
def test_home_url_resolves_home_view(self): view = resolve('/') self.assertEquals(view.func, home)
def test_category_resolve(self): self.assertEqual( resolve('/board/test-board-slug/test-category-slug').view_name, 'board:category')
def test_home_resolve(self): self.assertEqual(resolve('/board/').view_name, 'board:home')
def test_topic_resolve(self): self.assertEqual( resolve('/board/board-slug/category-slug/topic-slug').view_name, 'board:topic')
def test_redirect(): assert reverse("users:redirect") == "/users/~redirect/" assert resolve("/users/~redirect/").view_name == "users:redirect"
def test_board_resolve(self): self.assertEqual( resolve('/board/test-board-slug').view_name, 'board:board')
def test_register_url_resolves_to_register_view(self): """ - Testing if register url points to registerpage view """ url = resolve('/member/register') self.assertEqual(url.func, register)
def test_detail(user: User): assert (reverse("users:detail", kwargs={"username": user.username}) == f"/users/{user.username}/") assert resolve(f"/users/{user.username}/").view_name == "users:detail"
def test_admin_home_is_resolved(self): url = reverse('systemadministrator_home') self.assertEquals(resolve(url).func.view_class, AdminView)
def test_update(): assert reverse("users:update") == "/users/~update/" assert resolve("/users/~update/").view_name == "users:update"
def test_modifypassword_url_resolves_to_modifypassword_view(self): """ - Testing if modifypassword url points to modifypassword view """ url = resolve('/member/modifypassword') self.assertEqual(url.func, modifypassword)
def test_account_url_resolves_to_account_view(self): """ - Testing if account url points to accountpage view """ url = resolve('/member/account') self.assertEqual(url.func, account)
def test_home_url_resolves(self): url = reverse('home') self.assertEquals(resolve(url).func, index)
def test_disconnect_url_resolves_to_disconnect_view(self): """ - Testing if disconnect url points to disconnectpage view """ url = resolve('/member/disconnect') self.assertEqual(url.func, disconnect)
def test_url_for_postedit_using_viewname(self): url = reverse('post-edit', kwargs={'pk': 1}) assert resolve(url).view_name == 'post-edit'
def test_board_topics_url_resolves_board_topics_view(self): view = resolve(reverse('board_topics', kwargs={'pk': 1})) self.assertEquals(view.func.view_class, TopicListView)
def test_create_procedures_is_resolved(self): url = reverse('add_procedure') self.assertEquals(resolve(url).func, create_procedure)
def test_url_for_homepageview_using_view_classname(self): url = reverse('home') assert resolve(url).func.view_class == HomeView
def test_board_topics_url_resolves_board_topics_view(self): view = resolve('/boards/1/') self.assertEquals(view.func, board_topics)
def test_url_for_addpostview_using_viewname(self): url = reverse('add_post') assert resolve(url).view_name == 'add_post'