Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Write a test function that runs once before all test cases

Tags:

python

django

I have this code here that creates entries in the table because they're required in order to create a new post. You need a user and a goal and goal category. I heard setUp() runs before every test so that's an issue as it could try to great instances that already exists. I'd like to run setUp() once before all the tests are run. How do I do this?

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)

1 Answers

Actually for creating Django models the right answer is setupTestData() method. That method runs in database transaction which rolls back before the tests ends. Therefore all testing data are cleaned once the tests are done. The code is:

    @classmethod
    def setUpTestData(cls):
        GoalCategory.objects.create(category='other', emoji_url='url')
        cls.user = UserFactory()
        cls.goal = GoalFactory()
like image 198
Petr Dlouhý Avatar answered Sep 07 '25 21:09

Petr Dlouhý