How to test against UploadFile parameter

See original GitHub issue

First check

  • I added a very descriptive title to this issue.
  • I used the GitHub search to find a similar issue and didn’t find it.
  • I searched the FastAPI documentation, with the integrated search.
  • I already searched in Google “How to X in FastAPI” and didn’t find any information.
  • I already read and followed all the tutorial in the docs and didn’t find an answer.
  • I already checked if it is not related to FastAPI but to Pydantic.
  • I already checked if it is not related to FastAPI but to Swagger UI.
  • I already checked if it is not related to FastAPI but to ReDoc.
  • After submitting this, I commit to one of:
    • Read open issues with questions until I find 2 issues where I can help someone and add a comment to help there.
    • I already hit the “watch” button in this repository to receive notifications and I commit to help at least 2 people that ask questions in the future.
    • Implement a Pull Request for a confirmed bug.

Example

Here’s a self-contained, minimal, reproducible, example with my use case:

from fastapi import FastAPI

router = FastAPI()


@router.post("/_config")
def create_index_config(upload_file: UploadFile = File(...)):

    config = settings.reads()
    created_config_file: Path = Path(config.config_dir, upload_file.filename)

    try:
        with created_config_file.open('wb') as write_file:
            shutil.copyfileobj(upload_file.file, write_file)

    except Exception as err:
        raise HTTPException(detail=f'{err} encountered while uploading {upload_file.filename}',
                            status_code=HTTPStatus.INTERNAL_SERVER_ERROR)
    finally:
        upload_file.file.close()

    return JSONResponse({"message": f'uploaded config {upload_file.filename}'})

Description

I’m just trying to test against an endpoint that uses uploadfile and I can’t find how to send a json file to fastapi

def test_one():
  _test_upload_file = <path to file>
 with TestClient(app) as client:
        # TODO how to upload a file
        response = client.post('/_config',
                               data= <assuming something goes here ???> )
        assert response.status_code == HTTPStatus.CREATED

Environment

  • OS: [e.g. Linux / Windows / macOS]: OSX/docker
  • FastAPI Version [e.g. 0.3.0]: fastapi==0.54.1
  • Python version: Python 3.6.8

Additional context

data=_test_upload_file.open('rb') yields a 422 error I have also tried this and get a 422 error

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:18 (6 by maintainers)

github_iconTop GitHub Comments

11reactions
Kludexcommented, Jul 2, 2021

Here you have: https://stackoverflow.com/questions/60783222/how-to-test-a-fastapi-api-endpoint-that-consumes-images

Example:

with open(fpath, "wb") as f:
    response = client.post("/", files={"file": ("filename", f, "image/jpeg")})
10reactions
mwilson8commented, Jun 8, 2020

Big dumb on my part…

Working test:

_test_upload_file = Path('/usr/src/app/tests/files', 'new-index.json')
    _files = {'upload_file': _test_upload_file.open('rb')}
    with TestClient(app) as client:
        response = client.post('/_config',
                                files=_files)
        assert response.status_code == HTTPStatus.CREATED

    # remove the test file from the config directory
    _copied_file = Path('/usr/src/app/config', 'new-index.json')
    _copied_file.unlink()

I previously had the upload_file in the test named files – FYSA that name must match the parameter of your endpoint, in my case it’s upload_file so files wasn’t working

Read more comments on GitHub >

github_iconTop Results From Across the Web

How to test a FastAPI api endpoint that consumes images?
testclient import TestClient import.api_routers client = TestClient(api_routers.router) def test_prediction(constants): # Use constants if ...
Read more >
Testing - FastAPI
To pass a path or query parameter, add it to the URL itself. To pass a JSON body, pass a Python object (e.g....
Read more >
Test file upload in Selenium test
BrowserStack provides an option to test the file upload functionality for multiple scenarios using the LocalFileDetector method.
Read more >
File Upload
The operation payload is defined using formData parameters (not body parameters). The file parameter must have type: file : paths: /upload: post: summary: ......
Read more >
Testing file uploads with Postman (multipart/form-data)
I will show you how to debug an upload script and demonstrate it with a ... I do my best to answer all...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found