首页 > 解决方案 > Django - 编写一个在所有测试用例之前运行一次的测试函数

问题描述

我在这里有这段代码,它在表中创建条目,因为它们是创建新帖子所必需的。您需要一个用户以及一个目标和目标类别。我听说 setUp() 在每次测试之前都会运行,所以这是一个问题,因为它可以尝试已经存在的出色实例。我想在运行所有测试之前运行一次 setUp() 。我该怎么做呢?

class PostTest(TestCase):
    def setUp(self) -> None:
        GoalCategory.objects.create(category='other', emoji_url='url')
        self.user = UserFactory()
        self.goal = GoalFactory()

    def test_create_post(self):
        response = self.client.post(reverse('post'),
                                    data=json.dumps({'creator_id': str(self.user.uuid),
                                                     'goal_id': str(self.goal.uuid),
                                                     'body': 'Some text #Test'}),
                                    content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_no_goal_create_post(self):
        response = self.client.post(reverse('post'),
                                    data=json.dumps({'creator_id': str(self.user.uuid),
                                                     'goal_id': 'some messed up UUID',
                                                     'body': 'Some text #Test'}),
                                    content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

    def test_no_user_create_post(self):
        response = self.client.post(reverse('post'),
                                    data=json.dumps({'creator_id': 'messed up user',
                                                     'goal_id': str(self.goal.uuid),
                                                     'body': 'Some text #Test'}),
                                    content_type='application/json')
        self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

标签: pythondjango

解决方案


推荐阅读