from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status
from users.models import User
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"], "글 작성 완료")