7

Running a test on a url returns 302 instead of 200. Yet testing the same urls in production with a redirect tester returns 200. Not really sure what's going on.

tests.py

def test_detail(self):
    response = self.client.get('/p/myproduct-detail.html')
    self.assertEqual(response.status_code, 200)

urls.py

    url(r'^p/(?P<slug>[-\w\d]+).html$', main.views.product_detail, 
        name='product-detail'),

views.py

def product_detail(request, slug):
    stuff...
    return render(request, 'product-detail.html', {})

If I add follow=True to client.get() I receive 200 code as expected.

KingFu
  • 1,358
  • 5
  • 22
  • 42

1 Answers1

9

Print the value of response['location'] in your test before your assertEqual line. It will show you where the client is being redirected to (e.g. the login page).

def test_detail(self):
    response = self.client.get('/p/myproduct-detail.html')
    print(response['location'])
    self.assertEqual(response.status_code, 200)
Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • thanks, returns "/". Ah I think I've figured it out thanks to this, it must be raising a Http404() and redirecting to the index. This is my first time creating tests, I assumed it used a copy of the dev db but I now see this isn't the case! – KingFu Dec 07 '17 at 14:07
  • 1
    The test database that Django creates is not a copy of your dev db. You may have to create some objects in your test database before you run your tests, for example using [`setupTestData`](https://docs.djangoproject.com/en/1.11/topics/testing/tools/#django.test.TestCase.setUpTestData). – Alasdair Dec 07 '17 at 14:12
  • Thank you for mentioning this! I am using DjangoCMS and it prepended a '/de/' (so, my language prefix) before my actual URL. Took me hours to find this issue! -.- – Adrian Aug 25 '20 at 09:32