class ArticleReadTest(APITestCase)
만든다.setUpTestData(cls)
라는 @classmethod
를 이용해서 dummy data를 만든다.# articles/test.py
from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status
from users.models import User
from faker import Faker
# 이미지 업로드
from django.test.client import MULTIPART_CONTENT, encode_multipart, BOUNDARY
from PIL import Image
import tempfile
def get_temporary_image(temp_file):
size = (200, 200)
color = (255, 0, 0, 0)
image = Image.new("RGBA", size, color)
image.save(temp_file, 'png')
return temp_file
class ArticleCreateTest(APITestCase):
@classmethod
def setUpTestData(cls):
cls.user_data = {'email':'hp@gmail.com', 'password':'hp'}
cls.article_data = {'title':'hp', 'content':'hp is hp'}
cls.user = User.objects.create_user('hp@gmail.com', 'hp')
def setUp(self):
self.access_token = self.client.post(reverse('token_obtain_pair'), self.user_data).data['access']
def test_fail_if_not_logged_in(self):
url = reverse("article_view")
response = self.client.post(url, self.article_data)
self.assertEqual(response.status_code, 401)
def test_create_article(self):
response = self.client.post(
path=reverse("article_view"),
data=self.article_data,
HTTP_AUTHORIZATION=f"Bearer {self.access_token}"
)
self.assertEqual(response.status_code, 200)
def test_create_article_with_image(self):
temp_file = tempfile.NamedTemporaryFile()
temp_file.name = "image.png"
image_file = get_temporary_image(temp_file)
image_file.seek(0)
self.article_data["image"] = image_file
# 전송
response = self.client.post(
path=reverse("article_view"),
data=encode_multipart(data = self.article_data, boundary=BOUNDARY)
content_type=MULTIPART_CONTENT,
HTTP_AUTHORIZATION=f"Bearer {self.access_token}"
)
self.assertEqual(response.data["message"], "글 작성 완료")
# article 읽기
class ArticleReadTest(APITestCase):
@classmethod
def setUpTestData(cls):
cls.faker = Faker()
cls.articles = [] # 빈 리스트에 하나씩 append 한다.
for i in range(10): # 10명의 유저가 각 1개씩 글 작성하는 로직을 짠다.
# 새로운 유저 만들기; users/models.py에서 전개해준 부분
cls.user = User.objects.create_user(cls.faker.name(), cls.faker.word())
# articles에 새로운 글 추가하기
cls.articles.append(Article.objects.create(title=cls.faker.sentence(), content=cls.faker.text(), user=cls.user))
for문 반복할 때마다 새로운 cls.user
가 만들어지고 cls.articles.append
에 할당(저장)된다.
성능테스트를 할 경우, 여러 개의 dummy를 만들어서 할 수 있다.