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?"
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.
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.
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
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With