명령어
python manage.py test
python manage.py test users
등도 가능하다.
from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status
from users.models import User
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) # 에러메시지 등 알고 싶으면
self.assertEqual(response.status_code, 200)
# response로 온 status_code가 200인가?
# def test_login(self):
# url = reverse("token_obtain_pair") # name
# user_data = {
# "email":"gracia@gmail.com",
# "password":"divina"
# }
# response = self.client.post(url, user_data)
# print(response.data)
# self.assertEqual(response.status_code, 200)
# 원하는 유저모델로 로그인해서 나오게 하기
class LoginUserTest(APITestCase):
def setUp(self):
self.data = {'email':'happy@gmail.com', 'password':'happy'} # 로그인할 때 유저모델
self.user = User.objects.create_user('happy@gmail.com', 'happy')
def test_login(self):
response = self.client.post(reverse('token_obtain_pair'), self.data)
print(response.data["access"])
self.assertEqual(response.status_code, 200)
def test_get_user_data(self):
# access token을 받아와서 (.data['access'])
access_token = self.client.post(reverse('token_obtain_pair'), self.data).data['access']
response = self.client.get(
path=reverse("user_view"),
# 헤더에 넣어주는 방법으로.
HTTP_AUTHORIZATION=f"Bearer {access_token}"
)
print(response.data)
# self.assertEqual(response.status_code, 200)
self.assertEqual(response.data['email'], self.data['email'])
# 돌아온(조회된) 유저네임이 로그인할 때 사용한 유저네임과 동일한지
PS C:\Users\gracegoh\Desktop\drf1101> python manage.py test
Found 3 test(s).
Creating test database for alias 'default'...
System check identified no issues (0 silenced).
{'id': 1, 'password': 'pbkdf2_sha256$390000$ZAKFjL1ETFJCLwur4vCpQ0$ktTmRbgwjVndz/ckbO6wXGdBPjBiGn9PD1DENA2WqJ0=', 'last_login': None, 'email': 'happy@gmail.com', 'is_active': True, 'is_admin': False, 'followings': []}
.eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ0b2tlbl90eXBlIjoiYWNjZXNzIiwiZXhwIjoxNjY4NTU4OTk4LCJpYXQiOjE2Njg1MTU3OTgsImp0aSI6IjllOTk2MjAzNGMwMDQ5MDk4YTUxMWVlYmRlMWEyZDVlIiwidXNlcl9pZCI6MSwiZW1haWwiOiJoYXBweUBnbWFpbC5jb20ifQ.k4eDRmNig10OtMft3VIpyBI3FK9AlzMMDhBMBXTVPbk
.{'message': '회원가입이 완료되었습니다.'}
.
Ran 3 tests in 0.837s
OK
Destroying test database for alias 'default'...