如何测试send_file烧瓶

时间:2014-10-14 14:40:52

标签: python flask

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

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

我的Testclient:

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)

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

1 个答案:

答案 0 :(得分:10)

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

响应对象有一个名为' data'的属性,因此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()
相关问题