# user.test
def test_get_user_data(self):
access_token = self.client.post(reverse('token_obtain_pair'),self.data).data['access']
response = self.client.get(
path=reverse('user_view'),
HTTP_AUTHORIZATION=f"Bearer {access_token}"
)
self.assertEqual(response.status_code, 200)
# self.assertEqual(response.data['username'], self.data['username'])
# articles.tests.py
from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status
from users.models import User
# Create your tests here.
class ArticleCreateTest(APITestCase):
def setUp(self):
self.user_data = {'username': 'john', 'password':'johnpassword'}
self.article_data = {'title':'some title','content':'some content'}
self.user = User.objects.create_user('john','johnpassword')
self.access_token = self.client.post(reverse('token_obtain_pair'),self.user_data).data['access']
# articles.views.py
from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework import status
from rest_framework.response import Response
from articles.serializers import ArticleSerializer
from articles.models import Article as ArticleModel
# Create your views here.
class ArticleView(APIView):
def get(self, request):
articles = ArticleModel.objects.all()
serializer = ArticleSerializer(articles, many=True).data
return Response(serializer, status=status.HTTP_200_OK)
def post(self, request):
if not request.user.is_authenticated:
return Response({"message":"로그인 해주세요"}, 401)
serializer = ArticleSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response({"message": "글 작성 완료!!"})
else:
return Response({"message": f'${serializer.errors}'}, 400)
클래스메서드(class method)
예시) 사람 클래스와 메서드, 클래스메서드
Person 클래스는 이름과 나이를 속성으로 받는 클래스 객체다
Person 클래스에는 display메서드와 fromBirthYear 클래스메서드를 가지고 있다
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
@classmethod
def fromBirthYear(cls, name, birthyear):
return cls(name, date.today().year - birthyear)
def display(self):
print(self.name + "'s age is" + str(self.age))
변수에 Person 클래스를 선언하고 name과 age를 인자 값으로 넣어 사용할 수 있게 된 즉석 개체, 인스턴스를 생성했다.
클래스 인스턴스가 된 변수 person은 클래스 내부의 함수, 메서드를 사용할 수 있게 되어 display() 의 형식으로 함수를 호출하여 이름과 나이가 어떻게 되는지 프린트 해 볼 수 있다.
person = Person('Adam', 19)
person.display()
변수 person1은 인스턴스를 생성하지 않은 상태에서 바로 Person 클래스의 클래스메서드인 fromBirthYear를 name, birthyear 인자를 넣고 바로 호출했다.
클래스메서드 fromBirthYear는 입력한 인자와 함께 상위 클래스인 Person을 cls 인자로 받았다
return cls로 person1 변수로 초기화할 때 받았던 인자를 사용하여 클래스를 선언하는 형식에 맞게 값을 담아 인스턴스를 생성한다.
클래스메서드 return cls로 Person 클래스 인스턴스가 선언되었기 때문에, 클래스 내부의 함수인 display()를 변수 person1에서도 사용할 수 있게 되었다!
person1 = Person.fromBirthYear('John', 1985)
person1.display()
@staticmethod
def isAdult(age):
return age > 18
person1 = Person.fromBirthYear('황영상', 29) #클래스메서드의 활용
person1_is_adult = Person.isAdult(person1.age) #스태틱메서드의 활용
클래스메서드 setUpTestData와 메서드 setUp을 혼용해서 데이터 셋업하기

from django.test import TestCase
from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status
from users.models import User
# Create your tests here.
class ArticleCreateTest(APITestCase):
@classmethod
def setUpTestData(cls):
cls.user_data = {'username': 'john', 'password':'johnpassword'}
cls.article_data = {'title':'some title','content':'some content'}
cls.user = User.objects.create_user('john','johnpassword')
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)
python manage.py test articles
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.data['message'], "글 작성 완료!!")
# 이미지 업로드
from django.test.client import MULTIPART_CONTENT, encode_multipart, BOUNDARY
from PIL import Image
import tempfile
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),
content_type=MULTIPART_CONTENT,
HTTP_AUTORIZATION = f"Bearer {self.access_token}
)
self.assertEqual(response.data["message"], "글 작성 완료")