Skip to content

Instantly share code, notes, and snippets.

@lost-theory
Created September 23, 2012 17:48
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lost-theory/3772472 to your computer and use it in GitHub Desktop.
Save lost-theory/3772472 to your computer and use it in GitHub Desktop.
upload file with flask test client
import unittest
from app import app
from cStringIO import StringIO
class UploadTest(unittest.TestCase):
def setUp(self):
self.app = app
self.app.config['TESTING'] = True
self.client = self.app.test_client()
def test_upload(self):
res = self.client.post('/', data=dict(
upload_var=(StringIO("hi everyone"), 'test.txt'),
))
assert res.status_code == 200
assert 'file saved' in res.data
if __name__ == '__main__':
unittest.main()
@aaronshaver
Copy link

aaronshaver commented Jan 29, 2017

Helpful; thank you. Note though that you may need to upload it if you're using Python 3:

upload_var=(io.BytesIO(b'hi everyone'), 'test.csv'),

@kle91203
Copy link

kle91203 commented Aug 4, 2018

Perfect! Thank you.

@peterskipper
Copy link

This is helpful, thanks! Do you have code or a gist that shows how to write the POST endpoint which looks for upload_var?

@lost-theory
Copy link
Author

@PVinay737 you need to turn tracebacks on so you can see what's causing the 400 error. Here is what I've used in the past to do that:

https://github.com/lost-theory/moviepicker/blob/be36832/tests/__init__.py#L24

There's also a note on this in the flask docs on testing:

http://flask.pocoo.org/docs/0.12/testing/

Additionally during setup the TESTING config flag is activated. What it does is disable the error catching during request handling so that you get better error reports when performing test requests against the application.

Once you see the underlying traceback (instead of just the 400 error code) you will be able to see where the bug is (either in the way you're making the request in the test code, or if there's a problem in the view code, or something else).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment