무엇
에 관한 테스트코드 만들어야 하는지, 공식문서 참고하기
https://www.django-rest-framework.org/api-guide/testing/
테스트 대상은 views.py에서 작성한 코드다.
(python library나 django의 framework가 갖고 있는 code를 대상으로 테스트하지 않는다)
from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status
class UserRegisteationTest(APITestCase):
def test_registration(self):
url = reverse("user_view") # name에 해당하는 url을 가져온다.
user_data = {
"email":"happy@gmail.com",
"password":"happy"
}
response = self.client.post(url, user_data)
# print(response.data) 에러msg 알고 싶으면
self.assertEqual(response.status_code, 200)
def test_login(self):
url = reverse("token_obtain_pair") # name
user_data = {
"email":"happy@gmail.com",
"password":"happy"
}
response = self.client.post(url, user_data)
print(response.data)
self.assertEqual(response.status_code, 200)
모든 test는 독립적이다.
test method를 실행할 때마다 django는 DB를 초기화한다.
함수의 순서도 상관이 없기 때문에 아무것도 없는 상태에서 로그인하려고 하는 것과 같다.
print()
문은 개발 단계에서는 많이 만들지만
프로덕션 단계에서는 지워준다.
# users/test.py
class LoginUserTest(APITestCase):
def setUp(self):
self.data = {'email':'gracia@gmail.com', 'password':'divina'}
self.user = User.objects.create_user('gracia@gmail.com', 'divina') # 유저모델
def test_login(self):
response = self.client.post(reverse('token_obtain_pair'), self.data)
print(response.data["access"])
self.assertEqual(response.status_code, 200)
Found 2 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjY4NDc1NDM0LCJpYXQiOjE2Njg0MzIyMzQsImp0aSI6ImIxOWRjZDU5ZjI3MTRmMmI4MDhkZjdiNDgyZmNmYTJiIiwidXNlcl9pZCI6MSwiZW1haWwiOiJncmFjaWFAZ21haWwuY29tIn0.Ye1TvkzA_qlSqPJNo5wzTryXprSC3BPz8OYOnh8wYY4
Ran 2 tests in 0.520s
OK
Destroying test database for alias 'default'...