在 Flask 中测试文件上传

新手上路,请多包涵

我正在使用 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 许可协议

阅读 402
2 个回答

问题最终不是在将 content_type='multipart/form-data' 添加到 post 方法时,它期望 data 中的所有值都是文件或字符串。由于 这条 评论,我意识到我的数据字典中有整数。

所以最终的解决方案最终看起来像这样:

 def test_edit_logo(self):
    """Test can upload logo."""
    data = {'name': 'this is a name', 'age': 12}
    data = {key: str(value) for key, value in data.items()}
    data['file'] = (io.BytesIO(b"abcdef"), 'test.jpg')
    self.login()
    response = self.client.post(
        url_for('adverts.save'), data=data, follow_redirects=True,
        content_type='multipart/form-data'
    )
    self.assertIn(b'Your item has been saved.', response.data)
    advert = Item.query.get(1)
    self.assertIsNotNone(item.logo)

原文由 hammygoonan 发布,翻译遵循 CC BY-SA 3.0 许可协议

你需要两件事:

1.) content_type='multipart/form-data' 在你的 .post()

2.) 在你的 data= 传入 file=(BytesIO(b'my file contents'), "file_name.jpg")

一个完整的例子:

     data = dict(
        file=(BytesIO(b'my file contents'), "work_order.123"),
    )

    response = app.post(url_for('items.save'), content_type='multipart/form-data', data=data)

原文由 mmcclannahan 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏