}

Flask: How to Test file upload

Created:

Introduction

In this tutorial we are going to use the FlaskClient to test the api. FlaskClient will allow your test code to use the flask app like http requests.

Testing usign FlaskClient

In the code below we use the flask client to create a post request to upload a file. The variable data contains the proper data structure to "tell" the flask client that you want to simulate a file upload. We use assert for testing since we recommend to use pytest.

from io import BytesIO
from yourapp import app # IMPORT YOU FLASK APP HERE

def test_file_upload():
    client = app.test_client() # you will need your flask app to create the test_client
    data = {
        'file': (BytesIO('my file contents'), 'test_file.txt'), # we use StringIO to simulate file object
    }
    # note in that in the previous line you can use 'file' or whatever you want.
    # flask client checks for the tuple (<FileObject>, <String>)
    res = client.post('/upload', data=data) 
    assert res.status_code == 200

Another example to simulate a form post with file upload and some form fields:

app_client = app.test_client()
response = app_client.post('image/upload', buffered=True,
                           content_type='multipart/form-data',
                           data={'image_title' : 'New york from the top',
                                 'description' : 'Photo taken on nov 28 2017',
                                 'image_file' : (StringIO('IMAGE DATA'), 'new_york.jpg')})

Appendix: Flask app with file upload end point


app = Flask(__name__)

@app.route("/upload", methods=['POST'])
def upload():
    upload_file = request.files['file']
    content = upload_file.read() # do domething with the file uploaded
    upload_file.close()
    return 'ok'