Testing file uploads in Flask

前端 未结 4 421
庸人自扰
庸人自扰 2021-02-02 07:32

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 sayin

4条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 07:56

    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)
    

提交回复
热议问题