简体   繁体   English

如何在 Django 中测试 URL?

[英]How to test a URL in Django?

I wrote this detail view:我写了这个详细视图:

def blog_detail(request, pk):
    blog = get_object_or_404(Blog, pk=pk)
    comment = blog.comment_set.all()

    paginator = Paginator(comment, 2)

    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    context = {
        'blog': blog,
        'page_obj': page_obj,
    }

    return render(request, 'blog/blog_detail.html', context=context)

Here's the url:这是 url:

urlpatterns = [
    path('blog/<int:pk>/', views.blog_detail, name='blog-detail')
]

Here my test for the view:这是我对视图的测试:

class BlogDetailViewTest(TestCase):
    def setUp(self):
        user = User.objects.create(username='user01', password='123456')
        author = Author.objects.create(
            user=user, date_of_birth='1998-09-08', bio='I am user01')
        topic = Topic.objects.create(name='Testing')

        blog = Blog.objects.create(title='My blog', content="It's my blog")
        blog.author.add(author)
        blog.topic.add(topic)

        for c in range(3):
            Comment.objects.create(blog=blog, user=user, comment='I am testing')

        self.blog_instance = Blog.objects.get(id=1)

    def test_url(self):
        response = self.client.get(f'/blog/blog/{self.blog_instance.pk}')
        self.assertEqual(response.status_code, 200)

    def test_url_name(self):
        response = self.client.get(reverse('blog-detail', kwargs={'pk': self.blog_instance.pk}))
        self.assertEqual(response.status_code, 200)

The test_url function are returning this assertion error: test_url function 正在返回此断言错误:

AssertionError: 301 != 200

Why the test_url function are returning the status code 301 if the test_url_name function are returing the status code 200?如果 test_url_name function 正在返回状态代码 200,为什么 test_url function 返回状态代码 301? Both are the same url, I don't understand.两者都是同一个url,我不明白。

settings.py


APPEND_SLASH: bool = True # by default

It adds an extra / at the end of your URL[1].它在 URL[1] 的末尾添加了一个额外的/ That's why you are getting the redirect 301 response.这就是您收到重定向 301 响应的原因。 Setting APPEND_SLASH to False will give the test result you were expecting.APPEND_SLASH设置为False将给出您期望的测试结果。 Do run ./manage.py check --deploy .运行./manage.py check --deploy I'm not entirely sure how that would pan out in production.我不完全确定这将如何在生产中实现。

APPEND_SLASH ON THE DOCUMENTATION 在文档上添加 APPEND_SLASH

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

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