Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

flask

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

like image 940
VASIM SETA Avatar asked Dec 17 '15 09:12

VASIM SETA


People also ask

How do you send pictures through Flask?

Python for web development using Flask Handling file upload in Flask is very easy. It needs an HTML form with its enctype attribute set to 'multipart/form-data', posting the file to a URL. The URL handler fetches file from request. files[] object and saves it to the desired location.

How do you write a unit test case for Flask application?

First create a file named test_app.py and make sure there isn't an __init__.py in your directory. Open your terminal and cd to your directory then run python3 app.py . If you are using windows then run python app.py instead. Hope this will help you solve your problem.


2 Answers

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")
like image 106
Learner Avatar answered Oct 20 '22 01:10

Learner


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
        )
like image 25
Jack Riley Avatar answered Oct 19 '22 23:10

Jack Riley