I'm trying to test my upload() method in Flask. The only problem is that the FileStorage object in Flask has a method save() which the python File object does not have.
I create my file like this:
file = open('documents-test/test.pdf')
But I cannot test my upload() method because that method uses save().
Any ideas how to convert this File object to a Flask Filestorage object?
3 Answers
I needed to use the flask FileStorage object for a utility outside of the testing framework and the application itself, essentially replicating how uploading a file works using a form. This worked for me.
from werkzeug.datastructures import FileStorage
file = None
with open('document-test/test.pdf', 'rb') as fp:
file = FileStorage(fp)
file.save('document-test/test_new.pdf')
The get and post methods of the Flask test client invoke werkzeug.test.EnvironBuilder under the hood - so if you pass in a dictionary as the keyword argument data with your file you should be able to work with it then:
def test_upload():
with open("document-test/test.pdf", "rb") as your_file:
self.app.post("/upload", data={"expected_file_key": your_file})
# Your test here
@neurosnap 's answer got me started but didn't quite work. The following did...
file_loc = open('./tests/sample data/2 Candidates.csv', 'rb')
file = werkzeug.datastructures.FileStorage(file_loc)
file.save(dst='document-test/test_new.pdf')
file_loc.close()
Python throws an error if you don't close the file at the end.