如何在 Django 中测试 URL?

How to test a URL in Django?

我写了这个详细视图:

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)

这是url:

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

这里是我的视图测试:

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)

test_url 函数返回此断言错误:

AssertionError: 301 != 200

为什么 test_url 函数返回状态代码 301 而 test_url_name 函数返回状态代码 200?都是一样的url,没看懂

settings.py


APPEND_SLASH: bool = True # by default

它在 URL[1] 的末尾添加了一个额外的 /。这就是您收到重定向 301 响应的原因。将 APPEND_SLASH 设置为 False 将给出您期望的测试结果。执行 运行 ./manage.py check --deploy。我不完全确定这将如何在生产中实现。

APPEND_SLASH ON THE DOCUMENTATION