我有一个包含ImageField以及其他数据(整数,文本等)的模型。我有一个带有POST方法的API,可以使用图像文件创建数据。
问题是,如何测试包含imagefield的POST API。想要在测试文件而不是真实文件中创建伪造的图像,以及如何将其与其他数据一起进行测试。
serializer.py
class CategorySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Category
fields = ( 'id','name','description','parent_id','start','end')
read_only_fields = ('id','name','description','parent_id','start','end',)
class ServiceProviderSerializer(serializers. HyperlinkedModelSerializer):
category = CategorySerializer(many=True, read_only=True)
class Meta:
model = ServiceProvider
fields = (
'id',
'country_code',
'city',
'zip_code',
'service_type',
'preferred',
'display_bann',
'detail_name',
'detail_address',
'detail_description1',
'detail_description2',
'photo',
'category',
)
read_only_fields = ('id',)
def create(self, validated_data):
"""
Overriding the default create method of the Model serializer.
"""
# category_data = validated_data.pop('category')
category_data = self.context['request'].data.get('category')
service_provider = ServiceProvider.objects.create(**validated_data)
category_data = json.loads(category_data)
for category in category_data:
categoryObj = Category.objects.get(pk=category['id'])
service_provider.category.add(categoryObj)
return service_provider
test.py
def setUp(self):
self.new_service_provider = {
'country_code': "DE",
'city': "FRANKFURT AM MAIN",
'zip_code': 60435,
'service_type': "Fitness Studio",
'preferred': True,
'display_bann': "?",
'detail_name': "City Fitness Frankfurt",
'detail_address': "Trakehner Str. 5, 60487 Frankfurt am Main",
'detail_description1': "Based on review, we suggest you to go to this studio",
'detail_description2': "",
'category':[{'id':self.category1.pk}]
}
def test_post_service_provider(self):
self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.adminUser.auth_token.key)
# get API response
response = self.client.post(
reverse('service_provider-create'),
data=self.new_service_provider,
content_type='multipart/form-data'
)
print(response.data)
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
当前,由于我不知道如何模拟它,因此我尚未包括字段名称photo
。