Search code examples
djangodjango-urlsdjango-testingdjango-tests

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:

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:

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? Both are the same url, I don't understand.


Solution

  • settings.py

    
    APPEND_SLASH: bool = True # by default
    

    It adds an extra / at the end of your URL[1]. That's why you are getting the redirect 301 response. Setting APPEND_SLASH to False will give the test result you were expecting. Do run ./manage.py check --deploy. I'm not entirely sure how that would pan out in production.

    APPEND_SLASH ON THE DOCUMENTATION