Django 2.1 Test Issue

随声附和 提交于 2019-12-02 10:43:15

After researching a bit I came with the solution:

@classmethod
def setUpTestData(cls):
    Board.objects.create(name="Django", description="Django board.")

Instead of:

def setUp(self):
    self.board = Board(name="Django", description="Django board.")
    self.board.save()

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:

@classmethod
def setUpTestData(cls):
    self.board = Board.objects.create(name="Django", description="Django board.")

# Compruebo el status_code 200
def test_board_topics_view_status_code(self):
    url = reverse("board_topics", kwargs={"pk":self.board.pk})
    response = self.client.get(url)
    self.assertEqual(response.status_code, 200)

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:

  • Use setUpTestData instead setUp to add Data
  • Dont hardcode pk, store the object you already inserted and return the pk

Hope the answer helps!

Your's S3yk0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!