Testing file downloads with Flask and Python 3

I use Flask with Python 3.3, and I know that support is still experimental, but I encounter errors when trying to check file uploads. I am using unittest.TestCase and based on Python 2.7 examples that I saw in the documents I'm trying

 rv = self.app.post('/add', data=dict( file=(io.StringIO("this is a test"), 'test.pdf'), ), follow_redirects=True) 

and having received

 TypeError: 'str' does not support the buffer interface 

I tried several options around io.StringIO, but can't find anything that works. Any help is much appreciated!

Full stack trace

 Traceback (most recent call last): File "archive_tests.py", line 44, in test_add_transcript ), follow_redirects=True) File "/srv/transcript_archive/py3env/lib/python3.3/site-packages/werkzeug/test.py", line 771, in post return self.open(*args, **kw) File "/srv/transcript_archive/py3env/lib/python3.3/site-packages/flask/testing.py", line 108, in open follow_redirects=follow_redirects) File "/srv/transcript_archive/py3env/lib/python3.3/site-packages/werkzeug/test.py", line 725, in open environ = args[0].get_environ() File "/srv/transcript_archive/py3env/lib/python3.3/site-packages/werkzeug/test.py", line 535, in get_environ stream_encode_multipart(values, charset=self.charset) File "/srv/transcript_archive/py3env/lib/python3.3/site-packages/werkzeug/test.py", line 98, in stream_encode_multipart write_binary(chunk) File "/srv/transcript_archive/py3env/lib/python3.3/site-packages/werkzeug/test.py", line 59, in write_binary stream.write(string) TypeError: 'str' does not support the buffer interface 
+7
python flask unit-testing
source share
1 answer

In Python 3, you need to use io.BytesIO() (with a byte) to simulate the downloaded file:

 rv = self.app.post('/add', data=dict( file=(io.BytesIO(b"this is a test"), 'test.pdf'), ), follow_redirects=True) 

Note the line b'...' , which defines the bytes literal.

In Python test cases, the StringIO() object contains a byte string, not the unicode value, but in Python 3, io.BytesIO() is the equivalent.

+11
source share

All Articles