Testing file uploads in Flask

I use Flask-Testing for integration tests with Flask. I have a form in which there is a file for the logo that I am trying to write tests, but I continue to receive the error message: TypeError: 'str' does not support the buffer interface .

I am using Python 3. The closest answer I found is this one , but it does not work for me.

This is one of my many attempts:

 def test_edit_logo(self): """Test can upload logo.""" data = {'name': 'this is a name', 'age': 12} data['file'] = (io.BytesIO(b"abcdef"), 'test.jpg') self.login() response = self.client.post( url_for('items.save'), data=data, follow_redirects=True) }) self.assertIn(b'Your item has been saved.', response.data) advert = Advert.query.get(1) self.assertIsNotNone(item.logo) 

How to check file upload in Flask?

+6
source share
2 answers

The problem ended up when adding content_type='multipart/form-data' to the post method, all values ​​in data will either be files or strings. My dict data had integers that I realized thanks to this comment.

So, the final solution was as follows:

 def test_edit_logo(self): """Test can upload logo.""" data = {'name': 'this is a name', 'age': 12} data = {key: str(value) for key, value in data.items()} data['file'] = (io.BytesIO(b"abcdef"), 'test.jpg') self.login() response = self.client.post( url_for('adverts.save'), data=data, follow_redirects=True, content_type='multipart/form-data' ) self.assertIn(b'Your item has been saved.', response.data) advert = Item.query.get(1) self.assertIsNotNone(item.logo) 
+6
source

You need two things:

1.) content_type='multipart/form-data' in your .post()
2.) in your data= pass in file=(BytesIO(b'my file contents'), "file_name.jpg")

Full example:

  data = dict( file=(BytesIO(b'my file contents'), "work_order.123"), ) response = app.post(url_for('items.save'), content_type='multipart/form-data', data=data) 
+7
source

All Articles