django λ‘ νλ‘μ νΈ or μ±μ μμ±νκ² λλ©΄, test.py λΌλ νμΌμ΄ μμ±λλ€. μ΄ νμΌμ μ λ ν μ€νΈ νκΈ° μν νμΌμ΄λ€.
λ΄κ° μμ±ν μ½λμ κ°μ₯ μμ λ¨μμΈ ν¨μλ₯Ό ν
μ€νΈνλ λ©μλλ€.
μ½λλ₯Ό ν μ€νΈ νλ λ°©λ²μ μμ 3κ°μ§κ° μλ€.
μν 리μ€νΈ views μ§ λμ λ΄μ©μ λ°νμΌλ‘ unit testλ₯Ό μ§ννμλ€.
# views
class Allproducts(View):
def get(self,request):
product_all = Product.objects.all()
product_list = [{
'id' : product.id,
'category' : product.category,
'name' : product.name,
'heart_count' : product.heart_count,
'like' : product.like,
'retail_price' : product.retail_price,
'discount_percent' : product.discount_percent,
'monthly_pay' : product.monthly_pay,
'monthly_payment' : product.monthly_payment,
} for product in product_all]
return JsonResponse({'data':product_list}, status=200)
μμ μ½λλ μ 체 μν 리μ€νΈλ₯Ό λΆλ¬μ€λ λΆλ¬μ€λ viewsλ€.
μ΄λ₯Ό test.pyμ μμ±ν΄λ³΄λ©΄,
# test.py
import json
from django.test import TestCase, Client
from .models import Product
client = Client()
class AllproductsTest(TestCase):
def setUp(self):
Product.objects.create(
id = 1,
category = 'μ¬ν',
name = 'μ¬νμ λ λλ ν΄λμ€',
heart_count = 100,
like = 900000,
retail_price = 900000.0,
discount_percent = 50,
monthly_pay = 5,
monthly_payment = 10000,
)
def tearDown(self):
Product.objects.all().delete()
def test_Allproducts_get_success(self):
client = Client()
# get λ€μλ urlsμ μ€μ ν κ²½λ‘λ€
response = client.get('/products')
self.assertEqual(response.json(),
{
"data": [{
"id": 1,
"category": "μ¬ν",
"name": "μ¬νμ λ λλ ν΄λμ€",
"heart_count": 100,
"like": 900000,
"retail_price" : 900000.0,
"discount_percent": 50.0,
"monthly_pay": 5.0,
"monthly_payment": 10000
}]
}
)
self.assertEqual(response.status_code, 200)
μ€μ λ°μ΄ν°λ₯Ό λ£λ μ½λμ λ€μ μ§μ°λ μ½λ Product.objects.all().delete()
λ£μ΄μ£Όκ³ , test_Allproducts_get_success
ν¨μλ‘, μ λμκ°λμ§ λλ €μ€λ€.
μ΄μμ΄ μλ€λ©΄, OK κ° λ° κ²μ΄λ€.
μΆμ² : μμ½λ μΈμ λ§ν¬