VASIM SETA
VASIM SETA

Reputation: 165

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?"

Upvotes: 7

Views: 5379

Answers (2)

Jack Riley
Jack Riley

Reputation: 85

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
        )

Upvotes: 2

Learner
Learner

Reputation: 357

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")

Upvotes: 12

Related Questions