def test_process_resolver_recurses_for_nested_resolvers(wrap_fun):
    cb = Mock()
    resolver = URLResolver(RegexPattern(r'^foo/$'), [])
    resolver.callback = cb

    injector = Mock()
    process_resolver(URLResolver(RegexPattern(r'^$'), [resolver]), injector)
    wrap_fun.assert_has_calls([call(cb, injector)])
Пример #2
0
    def __init__(
        self,
        flag_name,
        regex,
        urlconf_name,
        default_kwargs=None,
        app_name=None,
        namespace=None,
        state=True,
        fallback=None,
    ):
        super(FlaggedURLResolver, self).__init__(
            regex,
            urlconf_name,
            default_kwargs=default_kwargs,
            app_name=app_name,
            namespace=namespace,
        )

        self.flag_name = flag_name
        self.state = state
        self.fallback = fallback
        self.fallback_patterns = []

        if isinstance(self.fallback, (list, tuple)):
            urlconf_module, app_name, namespace = self.fallback
            self.fallback_patterns = URLResolver(
                regex,
                urlconf_module,
                None,
                app_name=app_name,
                namespace=namespace,
            ).url_patterns
def test_process_resolver_repopulates_resolver():
    resolver = URLResolver(RegexPattern(r'^$'), [])
    resolver._populate()

    with patch.object(resolver, '_populate') as populate:
        process_resolver(resolver, Mock())
        populate.assert_called_once_with()
def test_process_resolver_wraps_resolver_callback(wrap_fun):
    resolver = URLResolver(RegexPattern(r'^$'), [])
    cb = Mock()
    resolver.callback = cb
    injector = Mock()
    process_resolver(resolver, injector)
    wrap_fun.assert_has_calls([call(cb, injector)])
Пример #5
0
    def process_request(request):

        resolver = URLResolver(RegexPattern(r'^/'), settings.ROOT_URLCONF)
        try:
            callback, callback_args, callback_kwargs = resolver.resolve(
                request.path)
            return callback(request, *callback_args, **callback_kwargs)
        except Resolver404 as e:
            pass
        except Http404 as e:
            return HttpResponseNotFound(str(e))

        return get_response(request)
def test_process_resolver_wraps_pattern_callbacks(wrap_fun):
    cb1 = Mock()
    pattern1 = URLPattern('', cb1)
    cb2 = Mock()
    pattern2 = URLPattern('', cb2)

    resolver = URLResolver(RegexPattern(r'^$'), [pattern1, pattern2])

    injector = Mock()
    process_resolver(resolver, injector)
    wrap_fun.assert_has_calls([
        call(cb1, injector),
        call(cb2, injector),
    ])
Пример #7
0
def detype_pattern(pattern):
    """
    return an equivalent pattern that accepts arbitrary values for path parameters.
    de-typing the path will ease determining a matching route without having properly
    formatted dummy values for all path parameters.
    """
    if isinstance(pattern, URLResolver):
        return URLResolver(
            pattern=detype_pattern(pattern.pattern),
            urlconf_name=[detype_pattern(p) for p in pattern.url_patterns],
            default_kwargs=pattern.default_kwargs,
            app_name=pattern.app_name,
            namespace=pattern.namespace,
        )
    elif isinstance(pattern, URLPattern):
        return URLPattern(
            pattern=detype_pattern(pattern.pattern),
            callback=pattern.callback,
            default_args=pattern.default_args,
            name=pattern.name,
        )
    elif isinstance(pattern, RoutePattern):
        return RoutePattern(
            route=re.sub(r'<\w+:(\w+)>', r'<\1>', pattern._route),
            name=pattern.name,
            is_endpoint=pattern._is_endpoint
        )
    elif isinstance(pattern, RegexPattern):
        detyped_regex = pattern._regex
        for name, regex in analyze_named_regex_pattern(pattern._regex).items():
            detyped_regex = detyped_regex.replace(
                f'(?P<{name}>{regex})',
                f'(?P<{name}>[^/]+)',
            )
        return RegexPattern(
            regex=detyped_regex,
            name=pattern.name,
            is_endpoint=pattern._is_endpoint
        )
    else:
        warn(f'unexpected pattern "{pattern}" encountered while simplifying urlpatterns.')
        return pattern
Пример #8
0
 def test_access_tenants(self):
     url_resolver = URLResolver(RegexPattern(''), "config.urls")
     resolve = url_resolver.resolve('api/tenants/')
     self.assertEqual(resolve.func.__name__, "TenantModelViewSet")
Пример #9
0
 def test_access_event(self):
     url_resolver = URLResolver(RegexPattern(''), "config.urls")
     resolve = url_resolver.resolve('api/event/')
     self.assertEqual(resolve.func.__name__, "event_execute")
Пример #10
0
 def test_access_notify(self):
     url_resolver = URLResolver(RegexPattern(''), "config.urls")
     resolve = url_resolver.resolve('api/notify/')
     self.assertEqual(resolve.func.__name__, "notify")
Пример #11
0
 def test_access_reset_password(self):
     url_resolver = URLResolver(RegexPattern(''), "config.urls")
     resolve = url_resolver.resolve('api/auth/reset/')
     self.assertEqual(resolve.func.__name__, "reset_password")
Пример #12
0
 def test_access_group_in_tenant(self):
     url_resolver = URLResolver(RegexPattern(''), "config.urls")
     resolve = url_resolver.resolve('api/tenants/1/notification-groups/')
     self.assertEqual(resolve.func.__name__, "NotificationGroupViewSet")
Пример #13
0
 def test_access_monitors_in_resources_in_awsenvs_in_tenant(self):
     url_resolver = URLResolver(RegexPattern(''), "config.urls")
     resolve = url_resolver.resolve(
         'api/tenants/1/aws-environments/1/regions/ap-northeast-1/services/ec2/resources/i-123456789/monitors/'
     )
     self.assertEqual(resolve.func.__name__, "MonitorViewSet")
 def reverse(self, pattern, name, *args, **kwargs):
     url_resolver = URLResolver(RegexPattern(r'^/'), urlconf_name=[pattern])
     return url_resolver.reverse(name, *args, **kwargs)
 def resolve(self, path, pattern):
     url_resolver = URLResolver(RegexPattern(r'^/'), urlconf_name=[pattern])
     return url_resolver.resolve(path)
Пример #16
0
 def test_access_users_in_tenant(self):
     url_resolver = URLResolver(RegexPattern(''), "config.urls")
     resolve = url_resolver.resolve('api/tenants/1/users/')
     self.assertEqual(resolve.func.__name__, "UserModeViewSet")
Пример #17
0
 def test_access_instances_in_awsenvs_in_tenant(self):
     url_resolver = URLResolver(RegexPattern(''), "config.urls")
     resolve = url_resolver.resolve(
         'api/tenants/1/aws-environments/1/resources/')
     self.assertEqual(resolve.func.__name__, "ResourceViewSet")
Пример #18
0
 def test_access_logs_in_tenant(self):
     url_resolver = URLResolver(RegexPattern(''), "config.urls")
     resolve = url_resolver.resolve('api/tenants/1/logs/')
     self.assertEqual(resolve.func.__name__, "OperationLogModelViewSet")
Пример #19
0
 def test_access_index(self):
     url_resolver = URLResolver(RegexPattern(''), "backend.urls")
     resolve = url_resolver.resolve('/')
     self.assertEqual(resolve.func.__name__, "HomePageView")
Пример #20
0
 def test_access_auth_refresh(self):
     url_resolver = URLResolver(RegexPattern(''), "config.urls")
     resolve = url_resolver.resolve('api/auth/refresh/')
     self.assertEqual(resolve.func.__name__, "RefreshJSONWebToken")
Пример #21
0
def get_filtered_apps(resolve_url="/", no_args=True, debug=False, skip_fail=False):
    """
    Filter settings.INSTALLED_APPS and create a list
    of all Apps witch can resolve the given url >resolve_url<

    @param resolve_url: url used for RegexURLResolver
    @param no_args: Only views without args/kwargs ?
    @parm skip_fail: If True: raise exception if app is not importable

    Please look at:

        django_tools.django_tools_tests.test_installed_apps_utils

    with debug, some print messages would be created:

    e.g.: get_filtered_apps(debug=True)
    found 'django.contrib.admindocs' with urls.py
    found 'django.contrib.auth' with urls.py
    Skip 'django.contrib.auth': Can't handle root url.
    found 'django.contrib.flatpages' with urls.py
    ['django.contrib.admindocs']
    """
    root_apps = []
    for app_label in settings.INSTALLED_APPS:
        urls_pkg = f"{app_label}.urls"
        try:
            url_mod = import_module(urls_pkg)
        except ImportError as err:
            if debug:
                print(f"Skip {app_label!r}: has no urls.py")
            if str(err) == f"No module named '{urls_pkg}'":
                continue
            if not skip_fail:
                raise
        except Exception as err:
            if debug:
                print(f"Error importing {app_label!r}: {err}")
            if not skip_fail:
                raise
            else:
                continue

        if debug:
            print(f"found {app_label!r} with urls.py")

        try:
            urlpatterns = url_mod.urlpatterns
        except AttributeError:
            if debug:
                print(f"Skip {app_label!r}: urls.py has no 'urlpatterns'")
            continue

        resolver = URLResolver(RegexPattern(r'^'), urlpatterns)
        try:
            func, func_args, func_kwargs = resolver.resolve(resolve_url)
        except Resolver404 as err:
            if debug:
                print(f"Skip {app_label!r}: Can't handle root url. ({err})")
            continue
        if not no_args or func_args == () and func_kwargs == {}:
            root_apps.append(app_label)
    return root_apps
Пример #22
0
def path_solver(settings):
    settings.DEBUG = True
    importlib.reload(project.urls)
    return URLResolver(RegexPattern(""), "project.urls")