Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Testing - Is this a safe way of writing my tests to avoid repeating long dictionaries in each test function

I'm new to Python and experimenting with writing some tests for an API endpoint. Is the way that I'm mocking the puppy object safe below? In my tests, it is working the way I'd expect. Do I run the risk in the future of the tests stepping on each other and the object's value that I think I'm testing, actually be referencing an older value in memory?

Should I be using a different strategy?

class PuppyTest(APITestCase):
    """ Test module for Puppy model """

    def mock_puppy(self):
        return {
            "name": "Max",
            "age": 3,
            "breed": "Bulldog"
        }

    def test_create_puppy_with_null_breed(self):
        """
        Ensure we can create a new puppy object with a null "breed" value
        """
        url = reverse('puppy')
        data = self.mock_puppy()
        data['breed'] = None # Updating breed value

        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

    def test_create_puppy(self):
        """
        Ensure we can create a new puppy object.
        """
        url = reverse('puppy')
        data = self.mock_puppy() # returns original "breed" value "Bulldog"

        response = self.client.post(url, data, format='json')
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
like image 549
dev-vsg Avatar asked Oct 16 '22 06:10

dev-vsg


1 Answers

Is the way that I'm mocking the puppy object safe below?

Yes

Do I run the risk in the future of the tests stepping on each other and the object's value that I think I'm testing, actually be referencing an older value in memory?

No

Should I be using a different strategy?

Your method is OK, with a new dict being created for each test. However, since you're using pytest, it might be more typical to put that data into a fixture rather than a method.

like image 117
wim Avatar answered Oct 20 '22 09:10

wim