Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
540 views
in Technique[技术] by (71.8m points)

python - How to test send_file flask

I have a small flask application which takes some images for upload and converts them into a multipage tiff. Nothing special.

But how do I test the upload of multiple files and the file download?

My 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()

The application sends back the file with

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

I want to read the file sent in the response and compare it with another file. How do I get the file from the response object?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think maybe the confusion here is that response is a Response object and not the data downloaded by the post request. This is because an HTTP response has other attributes that are often useful to know, for example http status code returned, the mime-type of the response, etc... The attribute names to access these are listed in the link above.

The response object has an attribute called 'data', so response.data will contain the data downloaded from the server. The docs I linked to indicate that data is soon to be deprecated, and the get_data() method should be used instead, but the testing tutorial still uses data. Test on your own system to see what works.Assuming you want to test a round trip of the data,

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...