def test_class_style_view(self, resolve): from django.urls import ResolverMatch from ..documents import SwaggerDoc view = ExampleView() resulve_match = ResolverMatch(func=view.get, args=[], kwargs={}) resulve_match.func_name = '{}.{}'.format(ExampleView.__module__, ExampleView.__name__) resolve.return_value = resulve_match swagger_doc = self._call_fut(url='/', method='get') self.assertIsInstance(swagger_doc, SwaggerDoc)
def resolve(self, path): ''' Different from Django, this method matches by /app/page/ convention using its pattern. The pattern should create keyword arguments for dmp_app, dmp_page. ''' match = super().resolve(path) if match: try: routing_data = RoutingData( match.kwargs.pop('dmp_app', None) or self.dmp.options['DEFAULT_APP'], match.kwargs.pop('dmp_page', None) or self.dmp.options['DEFAULT_PAGE'], match.kwargs.pop('dmp_function', None) or 'process_request', (match.kwargs.pop('dmp_urlparams', None) or '').strip(), ) if VERSION < (2, 2): return ResolverMatch( RequestViewWrapper(routing_data), match.args, match.kwargs, url_name=match.url_name, app_names=routing_data.app, ) else: return ResolverMatch( RequestViewWrapper(routing_data), match.args, match.kwargs, url_name=match.url_name, app_names=routing_data.app, route=str(self.pattern), ) except ViewDoesNotExist as vdne: # we had a pattern match, but we couldn't get a callable using kwargs from the pattern # create a "pattern" so the programmer can see what happened # this is a hack, but the resolver error page doesn't give other options. # the sad face is to catch the dev's attention in Django's printout msg = "◉︵◉ Pattern matched, but discovery failed: {}".format( vdne) log.exception("%s %s", match.url_name, msg) raise Resolver404({ # this is a bit convoluted, but it makes the PatternStub work with Django 1.x and 2.x 'tried': [[ PatternStub(match.url_name, msg, PatternStub(match.url_name, msg, None)) ]], 'path': path, }) raise Resolver404({'path': path})
def resolve(self, path): path = force_text(path) tried = [] match = self.regex.search(path) if match: new_path = path[match.end():] for pattern in self.url_patterns: try: sub_match = pattern.resolve(new_path) except Resolver404 as e: sub_tried = e.args[0].get('tried') if sub_tried is not None: tried.extend([pattern] + t for t in sub_tried) else: tried.append([pattern]) else: if sub_match: sub_match_dict = dict(match.groupdict(), **self.default_kwargs) sub_match_dict.update(sub_match.kwargs) return ResolverMatch( self._decorate(sub_match.func), sub_match.args, sub_match_dict, sub_match.url_name, self.app_name or sub_match.app_name, [self.namespace] + sub_match.namespaces) tried.append([pattern]) raise Resolver404({'tried': tried, 'path': new_path}) raise Resolver404({'path': path})
def _build_request(self, path, kwargs={}): request = RequestFactory().get(path) request.resolver_match = ResolverMatch(func=lambda: None, args=(), kwargs=kwargs) return request
def assertMenuCorrect(perm_name): request = rf.get("/admin/wechat_django/apps/" + str(self.app.id)) request.user = self._create_user(perm_name) request.app = self.app request.app_id = self.app.id request.resolver_match = ResolverMatch(lambda: None, tuple(), dict(app_id=self.app.id)) app_dict = site._build_app_dict(request, "wechat_django") permissions = pm.get_user_permissions(request.user, self.app) # 只有子权限是不会拥有菜单权限的 遂去掉子权限 permissions = { permission for permission in permissions if permission.find("_") == -1 and permission != "manage" } if permissions: all_permissions = { model["object_name"].lower().replace("wechat", "") for model in app_dict["models"] } self.assertEqual(permissions, all_permissions) else: self.assertIsNone(app_dict)
def test_cannnot_to_get_swaggerdoc(self, zope_resolve, dj_resolve): from django.urls import ResolverMatch resulve_match = ResolverMatch(func=None, args=[], kwargs={}) dj_resolve.return_value = resulve_match zope_resolve.return_value = None swagger_doc = self._call_fut(url='/', method='get') self.assertIsNone(swagger_doc)
def resolve(self, path): match = self.pattern.match(path) if match: new_path, args, kwargs = match name = kwargs.pop('name') if name not in registry: return view = registry[name] return ResolverMatch(view, args, kwargs, self.pattern.name)
def resolve(self, path): match = self.regex.search(path) if match: kwargs = match.groupdict() name = kwargs.pop('name') if name not in registry: return view = registry[name] return ResolverMatch(view, (), kwargs, self.name)
def test_func_style_view(self, resolve): from django.urls import ResolverMatch from ..documents import SwaggerDoc resulve_match = ResolverMatch(func=example_view, args=[], kwargs={}) resolve.return_value = resulve_match swagger_doc = self._call_fut(url='/', method='get') self.assertIsInstance(swagger_doc, SwaggerDoc)
def test_api_root_view_discard_default_django_model_permission(self): """ We check that DEFAULT_PERMISSION_CLASSES can apply to APIRoot view. More specifically we check expected behavior of ``_ignore_model_permissions`` attribute support. """ request = factory.get('/', format='json', HTTP_AUTHORIZATION=self.permitted_credentials) request.resolver_match = ResolverMatch('get', (), {}) response = api_root_view(request) self.assertEqual(response.status_code, status.HTTP_200_OK)
def _render_url(self, path, kwargs={}): request = RequestFactory().get(path) request.resolver_match = ResolverMatch(func=lambda: None, args=(), kwargs=kwargs) t = Template('{% load djblets_privacy %}' '{% pii_safe_page_url %}') return t.render(Context({ 'request': request, }))
def test_calendar_get_method(self): rf = RequestFactory() get_request = rf.get(path='/calendar/') get_request.user = self.user get_request.resolver_match = ResolverMatch(func=None, args=None, kwargs=None) get_request.resolver_match.url_name = 'calendar' with mock.patch.object( views, 'get_workouts_for_calendar') as calendar_mocked_method: calendar_mocked_method.return_value = [] response = views.calendar(get_request, '2017', '07') self.assertEqual(response.status_code, 200)
def hit_the_api(self): path = reverse("audio-list", kwargs={"version": "v3"}) request = RequestFactory().get(path) # Create the view and change the milestones to be something we can test # (Otherwise, we need to make 1,000 requests in this test) view = AudioViewSet.as_view({"get": "list"}) view.milestones = [1] # Set the attributes needed in the absence of middleware request.user = self.user request.resolver_match = ResolverMatch(view, {"version": "v3"}, "audio-list") view(request)
def handle_pk_parameter(resolved_route: ResolverMatch, path: str, method: str) -> Tuple[str, ResolverMatch]: """ Handle the DRF conversion of params called {pk} into a named parameter based on Model field """ coerced_path = BaseSchemaGenerator().coerce_path( path=path, method=method, view=cast(td.APIView, resolved_route.func)) pk_field_name = "".join( entry.replace("+ ", "") for entry in difflib.Differ().compare(path, coerced_path) if "+ " in entry) resolved_route.kwargs[pk_field_name] = resolved_route.kwargs["pk"] del resolved_route.kwargs["pk"] return coerced_path, resolved_route
def test_menu(self, admin_user): """ Test menu items with and without icons and with and without submenus """ path = '/' request = HttpRequest() request.path = path request.resolver_match = ResolverMatch(None, None, None, url_name='index') request.user = admin_user kwargs = {'request': request, 'user': admin_user} menu = utils.menu(**kwargs) assert menu == self.OUTPUT_MENU
def test_menu_on_detail_page(self, admin_user): path = reverse('articles:detail', kwargs={'pk': 1}) request = HttpRequest() request.path = path request.resolver_match = ResolverMatch(None, None, None, url_name='detail', app_names=['articles'], namespaces=['articles']) request.user = admin_user kwargs = {'request': request, 'user': admin_user} menu = utils.menu(**kwargs) assert dict(menu)['Articles']['active'] is True articles_submenu = dict(dict(menu)['Articles']['submenu']) assert articles_submenu['List']['active'] is True
def assertMenuCorrect(perm_name, manage=False, apps=None): request = rf.get("/admin/") request.user = self._create_user(perm_name) request.resolver_match = ResolverMatch(lambda: None, tuple(), dict()) app_dict = site._build_app_dict(request) if apps is None: apps = set([self.app.name]) if manage: self.assertEqual(len(app_dict["wechat_django"]["models"]), 1) else: self.assertNotIn("wechat_django", app_dict) if apps: appnames = { app["object_name"] for app in app_dict["wechat_django_apps"]["models"] } self.assertEqual(apps, appnames) else: self.assertNotIn("wechat_django_apps", app_dict)