首页 > 解决方案 > Fast api TestClient 发布文件列表

问题描述

我正在尝试测试获取文件列表的 fastapi 路由器。在使用 JS 的 html 请求中它的工作,但我需要测试它。我正在使用来自 fastapi 的 TestClient,当我尝试发送列表时,我得到状态代码 422,所以我去哪个文档并尝试 dict ,但我只得到 1 个文件的列表。

路由器

@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])

测试

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)

谢谢你的帮助

标签: pythonpython-requestsfastapiwebtestclient

解决方案


我在测试上传文件列表时遇到问题,我使用列表格式而不是 dict实现了它

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

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

推荐阅读