我是测试驱动开发的新手,并试图像这样测试一个端点:
url = '/v3/edm-list/extract/'
c = APIClient()
c.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key)
with open(test_email_list_path, 'rb') as eml, open(test_exclude_list_path, 'rb') as exl:
data = {
'tickers': tickers,
'email_list': eml,
'exlude_list': exl,
'exclude_keywords': exclude_keywords,
'simular_user_num': similar_user_num
}
response = c.post(url, data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
使用APIClient的帖子,我发送一个帖子请求到我的模型视图集:
class EDMListViewSet(viewsets.ModelViewSet):
queryset = EDMList.objects.all()
serializer_class = EDMListSerializer
随着模型:
class EDMList(models.Model):
tickers = models.CharField(max_length=512)
email_list = models.FileField(upload_to='edm_list/consolidated_emails')
exclude_list = models.FileField(upload_to='edm_list/excluded_emails')
exclude_keywords = models.CharField(max_length=512)
similar_user_num = models.IntegerField()
和序列化器:
class EDMListSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = EDMList
fields = ('tickers', 'email_list', 'exclude_list', 'exclude_keywords', 'similar_user_num')
现在每当我运行我的测试时,它返回:
Traceback (most recent call last):
self.assertEqual(response.status_code, status.HTTP_200_OK)
AssertionError: 400 != 200
但每当我打开可浏览的API并在那里发布时,我都能正确运行。我猜这个问题是我如何使用客户端的帖子,但我不知道我做错了什么。
我很惭愧承认这是一个印刷错误。由此:
data = {
'exlude_list': exl,
'simular_user_num': similar_user_num
}
对此:
data = {
'exclude_list': exl,
'similar_user_num': similar_user_num
}