Django Rest Framework api test upload text file application/



我正在尝试测试我的Django REST API进行文件上传。

问题是我的服务器尝试验证文件,以便该文件具有可识别的文件类型。目前只允许基于文本的文件类型,例如:docs,pdf,txt。

我尝试使用临时文件,现在我只是尝试从磁盘读取文件然后放弃了。

每当我使用临时文件时,服务器都会响应:

{
"cover_letter": [
"The submitted data was not a file. Check the encoding type on the form."
],
"manuscript": [
"The submitted data was not a file. Check the encoding type on the form."
]
}

这是我的测试:

def test_user_can_submit_a_paper(self):
"""
Ensure that an user is able to upload a paper.
This test is not working.. yet
"""
tmp_file = open("__init__.py", "w")
data = {
"title": "paper",
"authors": "me",
"description": "ma detailed description",
"manuscript": base64.b64encode(tmp_file.read()).decode(),
"cover_letter": base64.b64encode(tmp_file.read()).decode()
}
tmp_file.close()

response = self.client.post(self.papers_submitted, data=urlencode(MultiValueDict(data)), content_type='application/x-www-form-urlencoded',
HTTP_AUTHORIZATION=self.authorization_header)
print(response.data)
self.assertEqual(response.status_code, status.HTTP_200_OK)
del data["cover_letter"]
response = self.client.post(self.papers_submitted, data=urlencode(MultiValueDict(data)), content_type='application/x-www-form-urlencoded',
HTTP_AUTHORIZATION=self.authorization_header)
print(response.data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)

我已经通过邮递员成功测试了这个端点,但我不知道如何在 Python 中做到这一点。

如果我明白你在问什么,你想使用 python 通过文件上传来测试您的 DRF 端点。 你应该使用RequestFactory,它模拟一个请求——它更像是使用 Postman。

这个答案 Django:在 shell 中模拟 HTTP 请求有一个使用RequestFactory的例子,这里有多个答案 django RequestFactory 文件上传,用于有关如何将上传的文件包含在RequestFactory中的具体解决方案。

多亏了马克的回答,我设法想出了一个解决方案。 如果有人感兴趣,这是代码:

def test_user_can_submit_a_paper(self):
from api.journal import PaperListSubmitted
from django.test.client import RequestFactory
from django.core.files import temp as tempfile
"""
Ensure that an user is able to upload a paper.
"""
request_factory = RequestFactory()
manuscript = tempfile.NamedTemporaryFile(suffix=".txt")
cover_letter = tempfile.NamedTemporaryFile(suffix=".txt")
manuscript.write(b"This is my stupid paper that required me to research writing this test for over 5h")
cover_letter.write(b"This is my stupid paper that required me to research writing this test for over 5h")
manuscript.seek(0)
cover_letter.seek(0)
post_data = {
"title": "My post title",
"description": "this is my paper description",
"authors": "no authors",
"manuscript": manuscript,
"cover_letter": cover_letter
}
request = request_factory.post(self.papers_submitted, HTTP_AUTHORIZATION=self.authorization_header,
data=post_data)
response = PaperListSubmitted.as_view()(request)
self.assertEqual(response.status_code, status.HTTP_200_OK)

最新更新