Skip to content

Writing Django tests

Håvard Hellem edited this page Mar 16, 2018 · 2 revisions

Overview

Tests are located in appname/tests. API tests for different endpoints and such will be in different files under api/tests/.

API tests

Use the APITestCase class like so.

class ExampleTest(APITestCase):
    def setUp(self):
        """
        This method is called first and is used to set variables and such that are
        needed later and in all or most of the below methods.
        """
        # Creates a test user and makes it available for later.
        self.user = User.objects.create_user(username="name", password="testpassword")

    def test_post(self):
        # Authenticating a user with same credentials as above.
        self.client.login(username="name", password="testpassword")

        # Get endpoint url
        url = reverse(prod-data-list)
        # In `api/urls.py` the endpoint name is set. Then for revering it add the 
        # "method": 'retrieve' or 'list'.

        # Make a data variable
        data = [{put something in here}]

        # Send the POST request.
        response = self.client.post(url, data, format='json')

        # Check the status code
        self.assertEqual(response.status_code, status.HTTP_201_CREATED)

        # Check that the correct amount of db objects were created
        self.asserEqual(ModelName.objects.count(), <expected_number>)

The APITestCase class mirrors the standard TestCase class, but it uses the APIClient instead of Django's Client. APIClient extends Client.

General tests

Getting data from db

Make a query: data = ModelName.objects.all().

Serialize the query: serializer = ModelNameSerializer(data, many=True).

Set the many=True flag if the query returns more than one object.

Get the data from the serializer with serializer.data

Clone this wiki locally