Debian Codegraph @

tests/test_list_bytes_file_order_preserved_issue_14811.py

raw
1 """
2 Regression test: preserve order when using list[bytes] + File()
3 See https://github.com/fastapi/fastapi/discussions/14811
4 Fixed in PR: https://github.com/fastapi/fastapi/pull/14884
5 """
6
7 from typing import Annotated
8
9 import anyio
10 import pytest
11 from fastapi import FastAPI, File
12 from fastapi.testclient import TestClient
13 from starlette.datastructures import UploadFile as StarletteUploadFile
14
15
16 def test_list_bytes_file_preserves_order(
17 monkeypatch: pytest.MonkeyPatch,
18 ) -> None:
19 app = FastAPI()
20
21 @app.post("/upload")
22 async def upload(files: Annotated[list[bytes], File()]):
23 # return something that makes order obvious
24 return [b[0] for b in files]
25
26 original_read = StarletteUploadFile.read
27
28 async def patched_read(self: StarletteUploadFile, size: int = -1) -> bytes:
29 # Make the FIRST file slower *deterministically*
30 if self.filename == "slow.txt":
31 await anyio.sleep(0.05)
32 return await original_read(self, size)
33
34 monkeypatch.setattr(StarletteUploadFile, "read", patched_read)
35
36 client = TestClient(app)
37
38 files = [
39 ("files", ("slow.txt", b"A" * 10, "text/plain")),
40 ("files", ("fast.txt", b"B" * 10, "text/plain")),
41 ]
42 r = client.post("/upload", files=files)
43 assert r.status_code == 200, r.text
44
45 # Must preserve request order: slow first, fast second
46 assert r.json() == [ord("A"), ord("B")]