Search code examples
aiohttpsanic

Testing Sanic file Uploads


When looking at the docs I see a great examples of how you can test a sanic app.

# Import the Sanic app, usually created with Sanic(__name__)
from external_server import app

def test_index_returns_200():
    request, response = app.test_client.get('/')
    assert response.status == 200

def test_index_put_not_allowed():
    request, response = app.test_client.put('/')
    assert response.status == 405

Now I'm trying to get the testing framework to accept an uploaded photo to the endpoint. The code I have works via:

upload_payload = {'image':  open(os.path.join(img_dir, img_name), 'rb')}
request, response = app.test_client.post('/image', file = upload_payload)

It gives an error suggesting I cannot pass a file along. Does the testing framework not support this?


Solution

  • Turns out the standard for these sort of things is posting a data parameter along. This works just fine:

    upload_payload = {'image':  open(os.path.join(IMG_DIR, img_name), 'rb')}
    request, response = app.test_client.post('/image', data = upload_payload)