Tutorial to Write Tests For Django REST API endpoints - bounswe/bounswe2024group11 GitHub Wiki

How to write tests for Django REST API endpoints?

Unit Testing

Testing Views

  1. Create a folder named "tests" in your django app.
  2. Create an empty python file named "__init__.py" inside "tests" folder.
  3. Create a file to write tests. File name should start with "test" name.
    • Inside the file
      • from rest_framework.test import APITestCase
      • Create a class with name starting with "Test" inheriting APITestCase
      • In the urls.py file, give names as parameters in addition to paths and their views.
      • from django.urls import reverse to reverse the given names and obtain the absolute paths.
      • Create a method that has "test" in the beginning of its name.
      • Create a mock data to be sent using response = self.client.post(self.your_url_name, self.your_data, format='json')
      • You can see the response data using response.data or status using response.status_code
      • Use assertEqual to validate the test. Example: self.assertEqual(response.status_code, 200) for a request that is supposed to be successful.
      • You can create multiple test methods. They are run independent of each other.
      • run python manage.py test to run all of the tests.
      • Tests do not interact with your actual database. Example:
from rest_framework.test import APITestCase
from django.urls import reverse

class TestView(APITestCase):

    def test_add_user(self):
        self.add_user_url = reverse('add_user')
        self.user_data = {
            'username': "rider",
            'email': "[email protected]",
            'name': "ali",
            "surname": "yilmaz"
        }
        response = self.client.post(self.add_user_url, self.user_data, format='json')
        self.assertEqual(response.status_code, 200)

Additional Notes

  • You can install faker to generate random data. Example:
from faker import Faker
user_data = {
     'username': Faker().user_name(),
     'email': Faker().email(),
     'password': Faker().password(),
}