我正在为API做一些测试,这是代码:
tests.py
class APITest(APITestCase):
def setUp(self):
self.api_client = APIClient()
def test_get_lists(self):
response = self.api_client.get('/api/t/')
print(response.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
def test_post_list(self):
response = self.api_client.post('/api/t/',
data={'user':1, 'title':'AAA'})
print(response.data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
viewset.py
class TableViewset(ModelViewSet):
queryset = Table.objects.all()
serializer_class = TableSerializer
serializers.py
class TableSerializer(serializers.ModelSerializer):
lists = ListSerializer(many=True, read_only=True, required=False)
class Meta:
model = Table
fields = ('id', 'user', 'title', 'id', 'timestamp', 'lists')
def create(self, validated_data):
table = Table.objects.create(**validated_data)
return table
def update(self, instance, validated_data):
instance.title = validated_data.get('title', instance.title)
return instance
当我想在test.py中打印响应数据时,我得到一个空数组和一个OK测试 响应内容:
Response status_code=200, "application/json"
答案 0 :(得分:0)
好吧,解决方案是在测试中创建模型,因为在进行测试时我们无法使用db中的模型