Python/Django

[DRF] 14. 테스트 코드란?

눈표범꼬리 2023. 4. 27. 19:03

테스트 코드란?

    작성한 코드들이 원하는 값을 주는지 확인하는 코드

 

 

사용하는 이유

    1.버그를 쉽고 빠르게 찾을 수 있다.

    2. 코드가 얼마나 안전한지 확인할 수 있다.

    3. 코드의 복잡도를 낮출 수 있다.

    4. extreme programming (XP) 개념에서 중요하다.

          XP는 테스트 주도 개발(TDD) 방법을 사용한다. 지속적 통합(CI)과 지속적 배포(CD)를 지원하여 개발자들이 코드 변경 사항을 빠르게 수정할 수 있도록 하는데 목적이 있다.

    5. documentation화 제공한다.

          타인이 코드의 동작을 쉽게 이해하고 코드를 변경하면 문서화를 자동으로 업데이트 할 수 있다.

    6. performance(성능)를 체크한다.

          (ex, 시간이 얼마나 걸리는지)

 

 

 

 

 

Test Driven Development (테스트 주도 개발) 순서

   실패하는  테스트 코드 ->  테스트 코드를 성공시키기 위한 코드 작성 ->  refactoring (효율, 가독성)

 

 

사용 예시

py manage.py test <앱 이름>
# 앱 이름이 없으면 전체 test 코드를 실행
# 앱 이름이 있으면 앱의 test 코드만 실행

 

 

(app - test.py)

from django.test import TestCase


class TestView(TestCase):
    def test_two_is_three(self):
        # 2와 3이 같은지 확인
        self.assertEqual(2, 3)

 

 

https://www.django-rest-framework.org/api-guide/testing/

https://docs.djangoproject.com/en/4.2/topics/testing/overview/

https://docs.python.org/3/library/unittest.html#module-unittest

 

 

 

로그인 테스트 - 1

(app - test.py)

from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase

class UserRegistrationTest(APITestCase):
    def test_registration(self):
        # reverse : 해당 URL 패턴을 역으로 해석하여 URL 문자열을 반환하는 함수
        url = reverse('user_view')
        user_data = {
            "username" : "testuser",
            "fullname" : "테스터",
            "email" : "test@testuser.com",
            "password" : "password",
        }
        # 클라이언트로 post를 보냄
        # url로 user_data를 보냄
        response = self.client.post(url, user_data)
        # status 코드가 200인지 확인
        print(response.data)
        self.assertEqual(response.status_code, 200)

    def test_login(self):
        url = reverse('token_obtain_pair')
        user_data = {
            "username" : "testuser",
            "fullname" : "테스터",
            "email" : "test@testuser.com",
            "password" : "password",
        }
        response = self.client.post(url, user_data)
        print(response.data)
        self.assertEqual(response.status_code, 200)

    #{'detail': ErrorDetail(string='No active account found with the given credentials', code='no_active_account')}

 위에서 유저를 만들었는데 밑에서 로그인하니 에러가 난다.

 

이유

  • test 의 메소드를 실행할 때마다 DB 데이터를 초기화한다.
  • 테스트 코드의 실행 순서는 보장 되지 않는다.