Python & Django - Unit Test

Nina·2020년 11월 8일
2
post-thumbnail

1. Unit Test

Unit tests are typically automated tests written and run by software developers to ensure that a section of an application (known as the "unit") meets its design and behaves as intended.

유닛 테스트란, 작성한 코드의 가장 작은 단위의 함수를 테스트하는 메소드이다. 유닛 테스트를 함으로써 development cycle 초기에 문제를 발견하여 수정할 수 있고, 중장기적으로 유지 및 보수가 쉽다는 장점이 있다. 또한 UI 테스트나 Integration test보다 비용이 저렴하며 실행 속도가 빠르다.

2. Unit Test Example

(1) setUp() & tearDown()

from django.test import TestCase, Client
from user.models import User

import bcrypt
import json
# Create your tests here.
class UserTest(TestCase):

    def setUp(self):
        User.objects.create(
            name="Nina",
            password = bcrypt.hashpw("12345678".encode('utf-8'), bcrypt.gensalt()).decode('utf-8'),
            email = "lodger0812@naver.com",
            location_is_agreed = True,
            promotion_is_agreed = False
            )

    def tearDown(self):
        User.objects.all().delete()

테스트를 수행하기 전 setUp() 메소드를, 수행한 이후 tearDown() 메소드를 실행한다. 회원가입시 중복 확인/로그인 기능이 동작하는지 확인하기 위해선 테스트 수행 전 최소 한 명의 유저를 가입시켜야 한다. 이후 테스트가 완료되면 생성한 유저 데이터를 삭제한다.

(2) 회원가입

def test_EmailSignUpView_post_success(self):
        client = Client()
        user = {
            'name'                : 'ChaeYeong',
            'password'            : '12345678',
            'email'               : 'peridot9608@gmail.com',
            'location_is_agreed'  : True,
            'promotion_is_agreed' : False
        }
        response = client.post('/users/signup', json.dumps(user), content_type='application/json')

        self.assertEqual(response.status_code,200)

def test_EmailSignUpView_post_duplicated_email(self):
        client = Client()
        user = {
            'name'                : 'ChaeYeong',
            'password'            : '12345678',
            'email'               : 'lodger0812@naver.com',
            'location_is_agreed'  : True,
            'promotion_is_agreed' : False
        }
        response = client.post('/users/signup', json.dumps(user), content_type='application/json')

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json(),
        {"message": "EMAIL_EXISTS"}
        )

def test_EmailSignUpView_post_invalid_email(self):
        client = Client()
        user = {
            'name'                : 'ChaeYeong',
            'password'            : '12345678',
            'email'               : 'hwangninaagmail.com',
            'location_is_agreed'  : True,
            'promotion_is_agreed' : False
        }
        response = client.post('/users/signup', json.dumps(user), content_type='application/json')

        self.assertEqual(response.status_code, 400)
        self.assertEqual(response.json(),
        {"message": "INVALID_EMAIL"}
        )

📝test_EmailSignUpView_post_success(): 이메일로 회원가입이 성공하는 경우 상태코드 200이 반환되는지 확인한다.

📝test_EmailSignUpView_post_duplicated_email(): 이미 가입된 이메일인 경우 views.py에서 작성한 JsonResponse에 담긴 메시지({"message": "EMAIL_EXISTS"})와 상태코드 400이 반환되는지 확인한다.

📝test_EmailSignUpView_post_invalid_email(): 이메일이 조건을 만족시키지 않은 경우 올바른 JsonResponse 메시지({"message": "INVALID_EMAIL"})와 상태코드 400이 반환되는지 확인한다.

(3) 로그인

def test_EmailSigninView_post_success(self):
        client = Client()
        sign_in_user = {
            "email":"lodger0812@naver.com",
            "password":"12345678"
        }

        response = client.post('/users/signin', json.dumps(sign_in_user), content_type='application/json')

        self.assertEqual(response.status_code, 200)

def test_EmailSigninView_post_password_incorret(self):
        client = Client()
        sign_in_user = {    
            "email":"lodger0812@naver.com",
            "password":"11111111"
        }
        response = client.post('/users/signin', json.dumps(sign_in_user), content_type='application/json')

        self.assertEqual(response.status_code, 401)
        self.assertEqual(response.json(),
        {"message": "INVALID_PASSWORD"}
        )
    
def test_EmailSigninView_post_user_not_exists(self):
        client = Client()
        sign_in_user = {
            'email' : 'something@gmail.com',
            'password' : '19960812',
        }
        response = client.post('/users/signin', json.dumps(sign_in_user), content_type='application/json')

        self.assertEqual(response.status_code, 401)
        self.assertEqual(response.json(),
        {"message": "INVALID_USER"}
        )

📝test_EmailSigninView_post_success(): 로그인이 성공하면 상태코드 200을 반환한다.

📝test_EmailSigninView_post_password_incorret(): 이메일은 있으나 패스워드가 일치하지 않는 경우 올바른 JsonResponse 메시지({"message": "INVALID_PASSWORD"})와 상태코드 401을 반환한다.

📝test_EmailSigninView_post_user_not_exists(): 존재하지 않는 이메일인 경우 올바른 JsonResposne 메시지({"message": "INVALID_USER"})와 상태코드 401을 반환한다.

profile
https://dev.to/ninahwang

0개의 댓글