Debian Codegraph @

tests/test_file_and_form_order_issue_9116.py

raw
1 """
2 Regression test, Error 422 if Form is declared before File
3 See https://github.com/tiangolo/fastapi/discussions/9116
4 """
5
6 from pathlib import Path
7 from typing import Annotated
8
9 import pytest
10 from fastapi import FastAPI, File, Form
11 from fastapi.testclient import TestClient
12
13 app = FastAPI()
14
15
16 @app.post("/file_before_form")
17 def file_before_form(
18 file: bytes = File(),
19 city: str = Form(),
20 ):
21 return {"file_content": file, "city": city}
22
23
24 @app.post("/file_after_form")
25 def file_after_form(
26 city: str = Form(),
27 file: bytes = File(),
28 ):
29 return {"file_content": file, "city": city}
30
31
32 @app.post("/file_list_before_form")
33 def file_list_before_form(
34 files: Annotated[list[bytes], File()],
35 city: Annotated[str, Form()],
36 ):
37 return {"file_contents": files, "city": city}
38
39
40 @app.post("/file_list_after_form")
41 def file_list_after_form(
42 city: Annotated[str, Form()],
43 files: Annotated[list[bytes], File()],
44 ):
45 return {"file_contents": files, "city": city}
46
47
48 client = TestClient(app)
49
50
51 @pytest.fixture
52 def tmp_file_1(tmp_path: Path) -> Path:
53 f = tmp_path / "example1.txt"
54 f.write_text("foo")
55 return f
56
57
58 @pytest.fixture
59 def tmp_file_2(tmp_path: Path) -> Path:
60 f = tmp_path / "example2.txt"
61 f.write_text("bar")
62 return f
63
64
65 @pytest.mark.parametrize("endpoint_path", ("/file_before_form", "/file_after_form"))
66 def test_file_form_order(endpoint_path: str, tmp_file_1: Path):
67 response = client.post(
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
73 assert response.json() == {"file_content": "foo", "city": "Thimphou"}
74
75
76 @pytest.mark.parametrize(
77 "endpoint_path", ("/file_list_before_form", "/file_list_after_form")
78 )
79 def test_file_list_form_order(endpoint_path: str, tmp_file_1: Path, tmp_file_2: Path):
80 response = client.post(
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
89 assert response.json() == {"file_contents": ["foo", "bar"], "city": "Thimphou"}