Coverage for tests / test_file_and_form_order_issue_9116.py: 100%
39 statements
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
« prev ^ index » next coverage.py v7.13.3, created at 2026-02-12 18:15 +0000
1"""
2Regression test, Error 422 if Form is declared before File
3See https://github.com/tiangolo/fastapi/discussions/9116
4"""
6from pathlib import Path 1abdc
7from typing import Annotated 1abdc
9import pytest 1abdc
10from fastapi import FastAPI, File, Form 1abdc
11from fastapi.testclient import TestClient 1abdc
13app = FastAPI() 1abdc
16@app.post("/file_before_form") 1abdc
17def file_before_form( 1abdc
18 file: bytes = File(),
19 city: str = Form(),
20):
21 return {"file_content": file, "city": city} 1efg
24@app.post("/file_after_form") 1abdc
25def file_after_form( 1abdc
26 city: str = Form(),
27 file: bytes = File(),
28):
29 return {"file_content": file, "city": city} 1efg
32@app.post("/file_list_before_form") 1abdc
33def file_list_before_form( 1abdc
34 files: Annotated[list[bytes], File()],
35 city: Annotated[str, Form()],
36):
37 return {"file_contents": files, "city": city} 1hij
40@app.post("/file_list_after_form") 1abdc
41def file_list_after_form( 1abdc
42 city: Annotated[str, Form()],
43 files: Annotated[list[bytes], File()],
44):
45 return {"file_contents": files, "city": city} 1hij
48client = TestClient(app) 1abdc
51@pytest.fixture 1abdc
52def tmp_file_1(tmp_path: Path) -> Path: 1abdc
53 f = tmp_path / "example1.txt" 1abc
54 f.write_text("foo") 1abc
55 return f 1abc
58@pytest.fixture 1abdc
59def tmp_file_2(tmp_path: Path) -> Path: 1abdc
60 f = tmp_path / "example2.txt" 1abc
61 f.write_text("bar") 1abc
62 return f 1abc
65@pytest.mark.parametrize("endpoint_path", ("/file_before_form", "/file_after_form")) 1abdc
66def test_file_form_order(endpoint_path: str, tmp_file_1: Path): 1abdc
67 response = client.post( 1efg
68 url=endpoint_path,
69 data={"city": "Thimphou"},
70 files={"file": (tmp_file_1.name, tmp_file_1.read_bytes())},
71 )
72 assert response.status_code == 200, response.text 1efg
73 assert response.json() == {"file_content": "foo", "city": "Thimphou"} 1efg
76@pytest.mark.parametrize( 1abdc
77 "endpoint_path", ("/file_list_before_form", "/file_list_after_form")
78)
79def test_file_list_form_order(endpoint_path: str, tmp_file_1: Path, tmp_file_2: Path): 1abdc
80 response = client.post( 1hij
81 url=endpoint_path,
82 data={"city": "Thimphou"},
83 files=(
84 ("files", (tmp_file_1.name, tmp_file_1.read_bytes())),
85 ("files", (tmp_file_2.name, tmp_file_2.read_bytes())),
86 ),
87 )
88 assert response.status_code == 200, response.text 1hij
89 assert response.json() == {"file_contents": ["foo", "bar"], "city": "Thimphou"} 1hij