django - Pytest 图片上传 - 错误 rest_framework.exceptions.ParseError:多部分表单解析错误 - 多部分中的边界无效
问题描述
我正在测试一个将图像上传到用户配置文件的 API 调用。下面的测试用例返回状态码 400。如果我从数据中删除 image_filename 键,则测试用例成功。如何在 pytest 中测试图片上传?
def test_edit_user_profile(db, client):
# stream the image into binary
with open('C:/...../test.png', 'rb') as consultant_image:
image_binary = BytesIO(consultant_image.read())
userdetail_response = client.patch(path=reverse('user-detail', args="1"),
data={"full_name": "James edited",
"image_filename": (image_binary, 'test2.png')},
content_type='multipart/form-data',
HTTP_AUTHORIZATION='Token ' + data.json()['token_key'])
assert userdetail_response.status_code == status.HTTP_200_OK
解决方案
该解决方案有效
from django.test.client import BOUNDARY, MULTIPART_CONTENT, encode_multipart
userdetail_response2 = client.patch(
path=reverse('user-detail', args=(str(registered_response.json()['id']),)),
data=encode_multipart(BOUNDARY,
{
"full_name": "James",
"bio": "Details about me",
"is_allow_direct_order": False,
'image_filename': open((os.path.dirname(os.path.abspath(__file__))) + '/test.png', 'rb'),
}),
content_type=MULTIPART_CONTENT,
HTTP_AUTHORIZATION='Token ' + registered_response.json()['token_key']
)
推荐阅读
- node.js - 即使我在 Google App Engine 中设置了 {"type": "module"},也会出现“无法在模块外使用 import 语句”错误
- javascript - Blazor WASM Cookie 同意触发器 javascript
- ms-access - 安静地压缩 Access 文件
- php - 如何从单表 Laravel 中计算嵌套子级
- azure - 使用事件网格、函数和服务总线维护正确的顺序
- excel - 创建受保护的副本时使用密码隐藏不同范围的列
- django - ckeditor - 用户友好的图像上传
- kotlin - 为 textView Kotlin 格式化长文本
- unit-testing - 没有 PrepareForTest 的 PowerMockito whenNew
- python-3.x - 如何使用正则表达式仅获取关键字附近的日期