TIL
TIL.84 Unit Test_실습
codermun
2020. 12. 31. 15:25
728x90
반응형
이번 프로젝트에서는 반드시 내가 작성한 코드를 테스트하는 유닛테스트 코드를 함께 PR을 올려야 한다.
그럼 Wecode 자료를 이용해 실습을 해보도록 하자
아래 테스트 코드를 모두 fail -> success 로 바꿔보았으니
이를 이용해 나의 회원가입/로그인 뷰를 검증하는 테스트 코드를 만들어보자!

Test 1
# Test.1/ views.py
import json
from django.views import View
from django.http import HttpResponse, JsonResponse
class JustView(View):
def get(self, request):
return JsonResponse({'message':'Just Do Python with >Wecode'}, status = 200)
#Test.1 / tests.py
from django.test import TestCase, Client #테스트를 위한 클래스 임포트
client = Client() #client는 requests나 httpie가 일하는 방식과 같이 동작
하는 객체.
class JustTest(TestCase):
def test_just_get_view(self):
response = client.get('/just')
#현재 우리는 localhost로서가 아닌 기준 경로로부터 실행
self.assertEqual(response.status_code, 200)
#응답 코드를 비교
self.assertEqual(response.json(), {
"message": "Just Do Python with >Wecode"
})
#JSON 데이터를 비교
Test 2
# Test.2 / models.py
from django.db import models
class Book(models.Model):
title = models.CharField(max_length=50)
authors = models.ManyToManyField('Author', through = 'AuthorBook')
class Meta:
db_table = 'books'
class Author(models.Model):
name = models.CharField(max_length=50)
email = models.EmailField()
class Meta:
db_table = 'authors'
class AuthorBook(models.Model):
book = models.ForeignKey('Book', on_delete= models.SET_NULL, null=True)
author = models.ForeignKey('Author', on_delete= models.SET_NULL, null=True)
class Meta:
db_table = 'author_book'
class User(models.Model):
kakao = models.IntegerField(null=True)
facebook = models.IntegerField(null=True)
nick_name = models.CharField(max_length=25, unique=True)
email = models.CharField(max_length=50, null=True, unique=True)
password = models.CharField(max_length=400, null=True)
class Meta:
db_table = 'users'
# Test.2 / views.py
import json
import jwt
import requests
from django.views import View
from django.http import JsonResponse, HttpResponse
from .models import Book, Author, AuthorBook, User
class AuthorView(View):
def post(self, request):
data = json.loads(request.body)
try:
if Author.objects.filter(name = data["name"]).exists():
return JsonResponse({'message':'DUPLICATED_NAME'}, status = 400)
Author(
name = data['name'],
email = data['email']
).save()
return HttpResponse(status=200)
except KeyError:
return JsonResponse({'message':'INVALID_KEYS'}, status = 400)
class AuthorBookView(View):
def get(self, request, title):
try:
if Book.objects.filter(title = title).exists():
book = Book.objects.get(title = title)
authors = list(AuthorBook.objects.filter(book = book).values('author'))
return JsonResponse({'authors':authors}, status = 200)
return JsonResponse({'message':'NO_AUTHOR'}, status = 400)
except KeyError:
return JsonResponse({'message':'INVALID_KEYS'}, status = 400)
#Test.2 / tests.py
import json
import bcrypt
from .models import Book, Author, AuthorBook, User
from django.test import TestCase
from django.test import Client
from unittest.mock import patch, MagicMock
class AuthorTest(TestCase):
def setUp(self):
Author.objects.create(
name = 'Brendan Eich',
email = 'BrendanEich@gmail.com'
)
def tearDown(self):
Author.objects.all().delete()
def test_authorkview_post_success(self):
client = Client()
author = {
'name' : 'Guido van Rossum',
'email' : 'GuidovanRossum@gmail.com'
}
response = client.post('/book/author', json.dumps(author), content_type='application/json')
self.assertEqual(response.status_code, 200)
def test_authorkview_post_duplicated_name(self):
client = Client()
author = {
'name' : 'Brendan Eich',
'email' : 'GuidovanRossum@gmail.com'
}
response = client.post('/book/author', json.dumps(author), content_type='application/json')
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json(),
{
'message':'DUPLICATED_NAME'
}
)
def test_authorkview_post_invalid_keys(self):
client = Client()
author = {
'first_name' : 'Guido van Rossum',
'email' : 'GuidovanRossum@gmail.com'
}
response = client.post('/book/author', json.dumps(author), content_type='application/json')
self.assertEqual(response.status_code, 400)
self.assertEqual(response.json(),
{
'message':'INVALID_KEYS'
}
)
class AuthorBookTest(TestCase):
def setUp(self):
client = Client()
Book.objects.create(
id = 1,
title = 'python'
)
Book.objects.create(
id =2,
title = 'javascript'
)
Author.objects.create(
id = 1,
name = 'Guido van Rossum',
email = 'GuidovanRossum@gmail.com'
)
Author.objects.create(
id =2,
name = 'Brendan Eich',
email = 'BrendanEich@gmail.com'
)
AuthorBook.objects.create(
book = Book.objects.get(id=1),
author = Author.objects.get(id=1)
)
AuthorBook.objects.create(
book = Book.objects.get(id=1),
author = Author.objects.get(id=1)
)
AuthorBook.objects.create(
book = Book.objects.get(id=1),
author = Author.objects.get(id=2)
)
AuthorBook.objects.create(
book = Book.objects.get(id=2),
author = Author.objects.get(id=1)
)
AuthorBook.objects.create(
book = Book.objects.get(id=2),
author = Author.objects.get(id=2)
)
def tearDown(self):
Book.objects.all().delete()
Author.objects.all().delete()
AuthorBook.objects.all().delete()
def test_authorbook_get_success(self):
client = Client()
response = client.get('/book/author-book/python')
self.assertEqual(response.status_code, 200)
def test_authorbook_get_fail(self):
client = Client()
response = client.get('/book/author-book/c-language')
self.assertEqual(response.json(),
{
'message' : 'NO_AUTHOR'
}
)
self.assertEqual(response.status_code, 400)
def test_authorbook_get_not_found(self):
client = Client()
response = client.get('/book/author-book?book=python')
self.assertEqual(response.status_code, 404)
728x90
반응형