Reputation: 7765
I'm having trouble with testing my Django app. I can load a page in the browser just fine, but my test code returns 404.
This test returns False:
def test_item(self):
response = self.client.get('/items/1/')
self.assertEqual(response.status_code, 200)
If I stick a print line in there somewhere...
print(response)
... it returns the full HTML page, as expected:
Vary: Accept-Language, Cookie
Content-Type: text/html; charset=utf-8
Content-Language: en
<!DOCTYPE html>
...
</html>
Which looks good (should be 200) to me. But it's not:
print(response.status_code)
...returns 404
What am I missing?
Versions
Django 1.6, Python 2.7.6
URL
http://localhost:8000/items/1/
urls.py
urlpatterns = patterns('',
url(r"^(?P<item_id>[0-9]+/?)/$", "item.views.item_by_id",),
)
views.py
def item_by_id(request, item_id):
try:
item = Item.objects.get(id=item_id)
except Item.DoesNotExist:
raise Http404
return render(request, 'item.html', {'item': item})
Upvotes: 2
Views: 1799
Reputation: 8539
You don't have an item_id
that matches your url
(i.e., there's no "1" in your database). In your view, it's trying to get the Item
but it's raising an exception, thus returning an HTTP404
. The test and view is working exactly as it should.
Unit tests create a new (empty) database, so any Items
you have in your regular database won't appear. You'll need to create an Item
within your test file with the item_id
that you're checking.
Sample:
def test_item(self):
Item.objects.create(name="Item1") # Note you may need to edit the fields based on your model
response = self.client.get('/items/1/')
self.assertEqual(response.status_code, 200)
Upvotes: 7