-
Notifications
You must be signed in to change notification settings - Fork 1
Tutorial to Write Tests For Django REST API endpoints
Mücahit Erdoğan Ünlü edited this page Apr 27, 2024
·
2 revisions
- Create a folder named "tests" in your django app.
- Create an empty python file named "__init__.py" inside "tests" folder.
- 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 usingresponse.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:
- Inside the file
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)
- 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(),
}
Turquiz App
DONE
- Lab Report #1
- Lab Report #2
- Lab Report #3
- Lab Report #4
- Lab Report #5
- Lab Report #6
- Lab Report #7
- Lab Report for Lab 9
- Lab Meeting #1
- Meeting #1
- Lab Meeting #2
- Meeting #2
- Project Plan Meeting
- Frontend Meeting #1
- Lab Meeting #3
- Meeting #3
- Meeting #4
- Lab Meeting #4
- Meeting #5
- Meeting #6
- Meeting #7
- Meeting #8
- User Scenario 1 - Explore and Register
- User Scenario 2 - Search for a Quiz & Create a Quiz
- User Scenario 3 - Take & Review a Quiz
- User Scenario 4 - Search Forum & Bookmark & Upvote & Answer
- User Scenario 5 - User Badges
- User Scenario Template
- User Stories