Fast api TestClient post list of files

5.5k Views Asked by At

I am trying to test fastapi router that get List of files. In html request using JS its working but I need to test it. I am using TestClient from fastapi, when I am trying so send list I get status code 422 so I go which documentry and try dict but than I get list of only 1 file.

router

@router.post('/uploadone')
async def upload_file(response: Response,files:List = File(...)):
    try:

        properties = json.loads(files[len(files)-1])
        check_file_type(files[:len(files)-1])

test

def test_uploadone(self):
    with open('upload_data/system_test/properties.json', 'rb') as file1:
         json_file = json.load(file1)
    with open('upload_data/system_test/heatmap1.csv', 'rb') as file:
         body = file.read()
         response = self.client.post('/actions/uploadone',
                                        files={'files':('design_matrix1.csv', body),'json': 
                                              ('prop.json', json.dumps(json_file))})
         self.assertTrue(response.status_code == 200)

thanks for helping

2

There are 2 best solutions below

0
On

It seems like you should also add the multipart/form-data in the files.

response = self.client.post('/actions/uploadone', files={'files':('design_matrix1.csv', body, "multipart/form-data"),'json': ('prop.json', json.dumps(json_file))})

See

https://www.semicolonworld.com/question/43327/how-to-send-a-ldquo-multipart-form-data-rdquo-with-requests-in-python

NOTE

I also suggest you to split the data and the file parts, into two separate dictionaries, as in the example linked above

0
On

I had problems testing uploading a list of files, I achieved it using a list format instead of a dict

files = [
    ("parameter", ("file1.txt", BytesIO(b"aaa"))),
    ("parameter", ("file2.txt", BytesIO(b"bbb"))),
]

response = self.test_client.post("/api/upload", files=files)