Testing response of server, when the response changes between file and json


I have a flask server, that on one particular endpoint serves either a file for download with:

return send_file(pathAndFilename, as_attachment=True, attachment_filename = requestedFile)

or, if some condition fails, on error, it responds with a json message:

return make_response(json.dumps({'error_message': 'item does not exist'}), 400)

I want to test this endpoint with pytest.
How do i do this, since the response is different every time? How can i handle both cases?


I assume you’re doing some form of end-to-end testing on a route that returns a file. You should be able to create some canned data to feed into each of your tests (one pass, one intentional fail). Mock whatever function is generating your file to always return that canned data (you can always test the generation function later in other unit tests), and you should be able to produce consistent results.

Answered By – user3832673

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published