first of all thank you for your time and sorry about my english.
Im learning Django, I had several years developing with python and decided to start to check this Framework. And I'm getting an weird responses. Im writting a TestCase, wich works perfectly outside Test.
That is the code:
class BoardTopicsTests(TestCase):
# Hago las acciones necesarias para empezar el test
def setUp(self):
self.board = Board(name="Django", description="Django board.")
# self.board.save()
# Compruebo el status_code 200
def test_board_topics_view_status_code(self):
# self.board.save()
url = reverse("board_topics", kwargs={"pk":1})
response = self.client.get(url)
self.assertEqual(response.status_code, 200)
# Compruebo el status_code 404
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)
# Compruebo que resuelve bien el board
def test_board_topics_url_resolves_board_topics_views(self):
view = resolve("/boards/1/")
self.assertEqual( view.func.__name__, BoardTopics.as_view().__name__ )
If I save the board in setUp the method test_board_topics_view_status_code returns 404, if I save the board inside the method it returns 200 and pass the test.
I think I'm missing something because I think it have to work saving from setUp method!
Please, can somebody help with that? It's just for learning purposes because I want to know whats happening there.
If I do print(self.board.id) inside test_board_topics_view_status_code it returns 1 as it suposed to be.
Thank you very much!
After researching a bit I came with the solution:
Instead of:
It works BUT I'm trying to do the same with another class and the 404 still returns... In that particular TestCase works, in another ones dont,oO
I'm researching a bit more, I will write back if I found the "ultimate" solution hehehe.
UPDATE:
Well at the end I found the problem! The solution is the next one:
Note that in kwargs the value of pk is self.board.pk insteadof (and here where the error was) hardcoded 1 because we dont know if the PK would be 1!!! Oh that silly error took me one night without sleep.
So at the end we can resume in the next:
Hope the answer helps!
Your's S3yk0