Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

python - Testing file uploads in Flask

I'm using Flask-Testing for my Flask integration tests. I've got a form that has a file upload for a logo that I'm trying to write tests for but I keep getting an error saying: TypeError: 'str' does not support the buffer interface.

I'm using Python 3. The closest answer I have found is this but it's not working for me.

This is what one of my many attempts looks like:

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 does one test a file upload in Flask?

question from:https://stackoverflow.com/questions/35684436/testing-file-uploads-in-flask

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The issue ended up not being that when one adds content_type='multipart/form-data' to the post method it expect all values in data to either be files or strings. There were integers in my data dict which I realised thanks to this comment.

So the end solution ended up looking like this:

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...