【问题标题】:How to test send_file flask如何测试 send_file 烧瓶
【发布时间】:2014-12-09 09:53:54
【问题描述】:

我有一个小型烧瓶应用程序,它需要一些图像进行上传并将它们转换为多页 tiff。没什么特别的。

但是如何测试多个文件的上传和文件下载呢?

我的测试客户:

class RestTestCase(unittest.TestCase):
    def setUp(self):
        self.dir = os.path.dirname(__file__)
        rest = imp.load_source('rest', self.dir + '/../rest.py')
        rest.app.config['TESTING'] = True
        self.app = rest.app.test_client()

    def runTest(self):
        with open(self.dir + '/img/img1.jpg', 'rb') as img1:
            img1StringIO = StringIO(img1.read())

        response = self.app.post('/convert',
                                 content_type='multipart/form-data',
                                 data={'photo': (img1StringIO, 'img1.jpg')},
                                 follow_redirects=True)
        assert True

if __name__ == "__main__":
    unittest.main()

应用程序将文件发回

return send_file(result, mimetype='image/tiff', \
                                     as_attachment=True)

我想读取响应中发送的文件并将其与另一个文件进行比较。如何从响应对象中获取文件?

【问题讨论】:

  • rest.py 的内容是什么(或者它来自什么包),更具体地说,app.post 是什么样的?
  • rest.py 是我的烧瓶应用程序。 convert 方法,我在其中发布一些图像转换,并以调用 flask.send_file 结束。 app.post 是来自 flask.test_client 的方法。

标签: python flask


【解决方案1】:

我认为这里的混淆可能是response 是一个Response 对象,而不是发布请求下载的数据。这是因为 HTTP 响应具有其他通常有用的属性,例如返回的 http 状态代码、响应的 mime-type 等……访问这些属性的名称列在上面的链接中。

响应对象有一个名为“数据”的属性,因此response.data 将包含从服务器下载的数据。我链接的文档表明data 即将被弃用,应该使用get_data() 方法,但testing tutorial 仍然使用数据。在您自己的系统上进行测试,看看什么是有效的。假设您要测试数据的往返,

def runTest(self):
    with open(self.dir + '/img/img1.jpg', 'rb') as img1:
        img1StringIO = StringIO(img1.read())

    response = self.app.post('/convert',
                             content_type='multipart/form-data',
                             data={'photo': (img1StringIO, 'img1.jpg')},
                             follow_redirects=True)
    img1StringIO.seek(0)
    assert response.data == imgStringIO.read()

【讨论】:

  • 谢谢,帮了我很多。
  • 对于 Python 3,您应该在此处使用 BytesIO 而不是 StringIO,因为由于 mode='rb'img1 以二进制模式读取。
猜你喜欢
  • 2015-10-11
  • 1970-01-01
  • 2019-05-13
  • 2021-04-25
  • 2019-12-03
  • 2019-01-04
  • 2016-01-08
  • 2018-10-09
  • 1970-01-01
相关资源
最近更新 更多