[[oktatas:web:back-end_framework:django|< Django]]
====== Django REST API tesztelése ======
* **Szerző:** Sallai András
* Copyright (c) 2024, Sallai András
* Licenc: [[https://creativecommons.org/licenses/by-sa/4.0/|CC BY-SA 4.0]]
* Web: https://szit.hu
===== Teszt írása =====
Az emp könyvtárban készítsünk egy tests.py fájlt:
from . models import Employee
from rest_framework.test import APIClient
from rest_framework.test import APITestCase
from rest_framework import status
class EmployeeTestCase(APITestCase):
def setUp(self):
self.client = APIClient()
self.data = {
"name": "Erős István",
"city": "Szeged",
"salary": 395
}
self.url = "/employees"
def test_create_employee(self):
data = self.data
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertTrue(Employee.objects.count() > 0)
def test_create_employee_without_name(self):
data = self.data
data["name"] = ""
response = self.client.post(self.url, data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
==== Futtatás ====
python3 manage.py test
===== Kézi tesztelés =====
pip install requests
import requests
endpoint = 'http://localhost:8000/employees'
result = requests.get(endpoint)
print(result.json())
Futtatás:
python3 client.py