Skip to content

Instantly share code, notes, and snippets.

@lost-theory
Created September 23, 2012 17:48
Show Gist options
  • 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()
@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