Reputation: 1495
I'm trying to do simple tests in Django (v. 2.0.5). Since I can not see why I'm getting the '404 != 200' error, I post all relevant data.
test.py
from django.urls import resolve, reverse
from django.test import TestCase
from .views import home, board_topics
from .models import Board
class HomeTests(TestCase):
def test_home_view_status_code(self):
url = reverse('home')
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_home_url_resolves_home_view(self):
view = resolve('/home/')
self.assertEqual(view.func, home)
class BoardTopicsTests(TestCase):
def setUp(self):
Board.objects.create(name='Django', description='Django discussion board')
def test_board_topics_view_success_status_code(self):
url = reverse('board_topics', kwargs={'pk': 1})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
def test_board_topics_view_not_found_status_code(self):
url = reverse('board_topics', kwargs={'pk': 99})
response = self.client.get(url)
self.assertEqual(response.status_code, 404)
def test_board_topics_url_resolves_board_topics_view(self):
view = resolve('/boards/1/')
self.assertEqual(view.func, board_topics)
urls.py
from django.contrib import admin
from django.urls import include, path
from boards import views
urlpatterns = [
path('boards/<int:pk>/', views.board_topics, name='board_topics'),
path('home/', views.home, name='home'),
path('admin/', admin.site.urls),
]
views.py
...
def board_topics(request, pk):
try:
board = Board.objects.get(pk=pk)
except Board.DoesNotExist:
raise Http404
return render(request, 'topics.html', {'board': board})
Traceback
FAIL: test_board_topics_view_success_status_code (boards.tests.BoardTopicsTests)
----------------------------------------------------------------------
Traceback (most recent call last):
File "/.../boards/tests.py", line 25, in test_board_topics_view_success_status_code
self.assertEqual(response.status_code, 200)
AssertionError: 404 != 200
I wonder why I'm getting this error because I can call the views and I also get a 404 error when I try to call a page that does not exist (except Board.DoesNotExist). Is there a way to make the tests different (easier)? Thanks in advance for help.
Upvotes: 0
Views: 367
Reputation: 1
Use resolve('/')
instead of resolve('/home/')
def test_home_url_resolves_home_view(self):
view = resolve('/')
self.assertEquals(view.func, home)
Upvotes: 0
Reputation: 1143
You could try to adjust your test to automatically pickup the ID of the created object.
class BoardTopicsTests(TestCase):
def setUp(self):
self.board = Board.objects.create(name='Django', description='Django discussion board')
def test_board_topics_view_success_status_code(self):
url = reverse('board_topics', kwargs={'pk': self.board.id})
Maybe the database is not properly cleared between the tests?
Upvotes: 1