简体   繁体   English

在 Django context_processor 中测试 request.resolver_match

[英]Testing request.resolver_match in a Django context_processor

I have a Django context processor that puts the name of the current URL into the template context:我有一个 Django 上下文处理器,它将当前 URL 的名称放入模板上下文中:

def url_name(request):
    url_name = False
    if request.resolver_match:
        url_name = request.resolver_match.url_name
    return {"url_name": url_name}

This works - if I visit / then {{ url_name }} in the template will display "home" because I have a URL pattern like:这有效 - 如果我访问/那么模板中的{{ url_name }}将显示“home”,因为我有一个 URL 模式,例如:

path("", HomeView.as_view(), name="home"),

I would like to write a unittest for this context processor.我想为此上下文处理器编写一个单元测试。 I could do it like this:我可以这样做:

from django.test import Client, RequestFactory, TestCase
from myapp.context_processors import url_name

class URLNameTestCase(TestCase):
    def test_url_name(self):
        response = Client().get("/")
        self.assertEqual(response.context["url_name"], "home")

That succeeds, but I'd like to unitttest the url_name() method on its own, outside of the response cycle.这成功了,但我想在响应周期之外自行对url_name()方法进行单元测试。

I've tried this:我试过这个:

class URLNameTestCase(TestCase):
    def test_url_name(self):
        request = RequestFactory().get("/")
        context = url_name(request)
        self.assertEqual(context["url_name"], "home")

But that fails because, in this situation, within url_name() , request.resolver_match is None .但这失败了,因为在这种情况下,在url_name()中, request.resolver_matchNone Why is that?这是为什么?

since you try to get urlname by urlpath you should link your request with some view, you can do it to set "resolver_match" attribute like that:由于您尝试通过 urlpath 获取 urlname,您应该将您的请求与某个视图链接,您可以这样做来设置“resolver_match”属性,如下所示:

from django.urls import resolve

...

class URLNameTestCase(TestCase):
    def test_url_name(self):
        request = RequestFactory().get("/")
        request.resolver_match = resolve("/")
...

You create a request using a RequestFactory but it doesn't mean that your request is linked with any view, to link your request with some view you need to set resolver_match to your request.您使用 RequestFactory 创建请求,但这并不意味着您的请求与任何视图链接,要将您的请求与您需要将 resolver_match 设置为您的请求的某些视图链接。

Read more:阅读更多:

Link 1 链接 1

Link 2 链接 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM