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)
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With