简体   繁体   中英

How to send image with form data in test case with unittest in flask application?

I am newer to Python, I am making Flask application. so, I want to write Test Cases for my application using unittest, and I am doing like this:

def test_bucket_name(self):
    self.test_app = app.test_client()
    response = self.test_app.post('/add_item', data={'name':'test_item','user_id':'1','username':'admin'})                                      
    self.assertEquals(response.status, "200 OK")

It is all work well. But I am posting some data and image with POST in one URL. So, My Question is that : " How do i send image with that data? "

Read the image into a StringIO buffer. Pass the image as another item in the form data, where the value is a tuple of (image, filename).

def test_bucket_name(self):
    self.test_app = app.test_client()

    with open('/home/linux/Pictures/natural-scenery.jpg', 'rb') as img1:
        imgStringIO1 = StringIO(img1.read())

    response = self.test_app.post('/add_item',content_type='multipart/form-data', 
                                    data={'name':'test_item',
                                          'user_id':'1',
                                          'username':'admin',
                                          'image': (imgStringIO1, 'img1.jpg')})
    self.assertEquals(response.status, "200 OK")

The above answer is correct, except in my case I had to use BytesIO like the following:

    def create_business(self, name):
        with open('C:/Users/.../cart.jpg', 'rb') as img1:
            imgStringIO1 = BytesIO(img1.read())
        return self.app.post(
            '/central-dashboard',
            content_type='multipart/form-data',
            data=dict(name=name, logo=(imgStringIO1, 'cart.jpg')),
            follow_redirects=True
        )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM