lundi 29 juin 2020

How can I test CSV uploader API that developed by Flask (without mock)?

I try to test my CSV uploader POST API endpoint that implemented with Flask, but I can't simulate the same behavior that I do when sending CSV file to API by curl.

Simple API endpoint by Flask:

@app.route("/uploader", methods=["POST"])
def csv_uploader():
    csv_file = next(iter(request.files.values()))  
    stream = io.StringIO(csv_file.stream.read().decode("utf-8"), newline=None)
    data = []

    for data_row in csv.DictReader(stream):
        data.append(data_row)
    
    return {"message": f"({len(data)}) data row were uploaded!"}

Curl command that I use:

curl -F 'file=@./file.csv' 127.0.0.1:5000/uploader

Additional information: The requests.files ( that give us the flask ) is ImmutableMultiDict([('f', <FileStorage: 'file.csv' ('application/octet-stream')>)])

My attempt of test:

def test_endpoint_works_as_expected(self, client):
test_csv_file = FileStorage(
    stream=BytesIO("id,first_name\n1,jakab".encode("utf-8")).read(),
    filename="test_financial_file.csv",
)

resp = client.post(
    "/uploader", 
    data={"file": test_financial_file},
    headers={'Content-Type': 'application/octet-stream'}
)

assert resp.status_code == 200
assert resp.json == {"message": "(1) data row were uploaded!"}

( where the client is a Flask test-client fixture and FileStorage is a data structure that werkzeug gives us )

The problem is that even though I send the request to my API, nothing arrives in the files of Flask's request object.

How can I test my uploader API and simulate the behavior of file upload? ( without mocking )

Aucun commentaire:

Enregistrer un commentaire