我正在使用 Flask-Testing 进行我的 Flask 集成测试。我有一个表单,其中有一个徽标的文件上传,我正在尝试为其编写测试,但我不断收到一条错误消息: TypeError: 'str' does not support the buffer interface
。
我正在使用 Python 3。我找到的最接近的答案是 这个,但它对我不起作用。
这是我的许多尝试之一:
def test_edit_logo(self):
"""Test can upload logo."""
data = {'name': 'this is a name', 'age': 12}
data['file'] = (io.BytesIO(b"abcdef"), 'test.jpg')
self.login()
response = self.client.post(
url_for('items.save'), data=data, follow_redirects=True)
})
self.assertIn(b'Your item has been saved.', response.data)
advert = Advert.query.get(1)
self.assertIsNotNone(item.logo)
如何测试 Flask 中的文件上传?
原文由 hammygoonan 发布,翻译遵循 CC BY-SA 4.0 许可协议
问题最终不是在将
content_type='multipart/form-data'
添加到post
方法时,它期望data
中的所有值都是文件或字符串。由于 这条 评论,我意识到我的数据字典中有整数。所以最终的解决方案最终看起来像这样: