본문 바로가기
TTL/9주차 ~ 12주차 TIL (10.24 ~ 11.18)

2022-11-14 TIL (django 테스트코드 작성하기)

by dev_junseok 2022. 11. 14.

장고 프로젝트를 할 때, 앱을 생성하게 되는데 앱을 생성하면 기본적으로 test.py라는 파일이 생기는것을 볼 수 있다.

 

이게 뭐냐 하면 내가 만든 코드들을 테스트 하는 공간이다.

 

테스트코드를 작성하여 내 코드들을 테스트 하면, 시간이 매우 절약되고 내 코드들은 document화(문서화) 시키는데 용이하다.

 

Testing in Django | Django documentation | Django (djangoproject.com)

 

Testing in Django | Django documentation | Django

Django The web framework for perfectionists with deadlines. Toggle theme (current theme: auto) Toggle theme (current theme: light) Toggle theme (current theme: dark) Toggle Light / Dark / Auto color theme Overview Download Documentation News Community Code

docs.djangoproject.com

Testing - Django REST framework (django-rest-framework.org)

 

Testing - Django REST framework

 

www.django-rest-framework.org

해당 공식문서들에 정보가 많이 있다.

 

회원가입, 로그인 기능의 테스트 코드들을 작성해 보았다. 회원가입 로그인은 simplejwt를 이용하여 구현하였다.

class UserRegistrationTest(APITestCase):
    def test_registration(self):  #회원가입 테스트
        url = reverse("user_view")   # url name
        user_data = {
            "username": "testuser",
            "fullname": "테스터",
            "email": "test@test.com",
            "password":"1234",
        }
        response = self.client.post(url, user_data)  # APITestCase의 기본적인 세팅
        self.assertEqual(response.status_code, 200)
    


class LoginUserTest(APITestCase):
    def setUp(self):  # DB 셋업
        
        self.data = {'username': 'john', 'password': 'johnpassword'}
        self.user = User.objects.create_user('john', 'johnpassword')
    
    def test_login(self):   # 로그인 테스트
        response = self.client.post(reverse('token_obtain_pair'), self.data)
        self.assertEqual(response.status_code, 200)
    
    def test_get_user_data(self): # 유저정보 조회 테스트
        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['username'], self.data['username'])

아래쪽 코드를보면 setUp이라고 있는데, 이건 로그인을 하기 위해 더미데이터를 만들어 둔다고 생각하면 된다.

테스트코드들은 전부 분리되어서 실행되기 때문에, 회원가입할때 넣은 데이터들이 로그인 테스트코드까지 오지 않는다.

 

다음으로는 assertEqual 함수를 사용하여 코드가 정상적으로 작동하는지 확인한다. 해당코드들은 http status code를 비교하여 테스트 하였다.

 

 솔직히 아직까지는 테스트코드의 중요성은 알겠지만 제대로 쓰고 있지는 못한다... 더 공부해야겠다