1) models.py 작성
from django.db import models
class User(models.Model):
name = models.CharField(max_length=100)
class Meta:
db_table = 'users'
2) views.py 작성
from django.views import View
from django.http import JsonResponse
from .models import User
class UserView(View):
def get(self, request, id):
if User.objects.filter(id=id).exists():
user = User.objects.get(id=id)
return JsonResponse({'name': user.name}, stauts=200)
return JsonResponse({'message':'no user'}, status=400)
3) tests.py 작성
[test.py]
from django.test import TestCase, Client
from .models import User
class UserTest(TestCase):
def setUp(self):
client = Client() # 클라이언트 초기화
User.objects.create(name='john')
def tearDown(self):
User.objects.all().delete()
def test_get_user_view(self):
response = self.client.get('/user/1')
self.assertEqual(response.status_code, 200)
self.assertEqual(response.json(), {'name':'john'}
4) 실행