Coverage for tests/test_datastructures.py: 100%
51 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-12-04 08:29 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-12-04 08:29 +0000
1import io 1hijklmn
2from pathlib import Path 1hijklmn
3from typing import List 1hijklmn
5import pytest 1hijklmn
6from fastapi import FastAPI, UploadFile 1hijklmn
7from fastapi.datastructures import Default 1hijklmn
8from fastapi.testclient import TestClient 1hijklmn
11# TODO: remove when deprecating Pydantic v1
12def test_upload_file_invalid(): 1hijklmn
13 with pytest.raises(ValueError): 1JKLMNOP
14 UploadFile.validate("not a Starlette UploadFile") 1JKLMNOP
17def test_upload_file_invalid_pydantic_v2(): 1hijklmn
18 with pytest.raises(ValueError): 1QRSTUVW
19 UploadFile._validate("not a Starlette UploadFile", {}) 1QRSTUVW
22def test_default_placeholder_equals(): 1hijklmn
23 placeholder_1 = Default("a") 1vwxyzAB
24 placeholder_2 = Default("a") 1vwxyzAB
25 assert placeholder_1 == placeholder_2 1vwxyzAB
26 assert placeholder_1.value == placeholder_2.value 1vwxyzAB
29def test_default_placeholder_bool(): 1hijklmn
30 placeholder_a = Default("a") 1CDEFGHI
31 placeholder_b = Default("") 1CDEFGHI
32 assert placeholder_a 1CDEFGHI
33 assert not placeholder_b 1CDEFGHI
36def test_upload_file_is_closed(tmp_path: Path): 1hijklmn
37 path = tmp_path / "test.txt" 1abcdefg
38 path.write_bytes(b"<file content>") 1abcdefg
39 app = FastAPI() 1abcdefg
41 testing_file_store: List[UploadFile] = [] 1abcdefg
43 @app.post("/uploadfile/") 1abcdefg
44 def create_upload_file(file: UploadFile): 1abcdefg
45 testing_file_store.append(file) 1abcdefg
46 return {"filename": file.filename} 1abcdefg
48 client = TestClient(app) 1abcdefg
49 with path.open("rb") as file: 1abcdefg
50 response = client.post("/uploadfile/", files={"file": file}) 1abcdefg
51 assert response.status_code == 200, response.text 1abcdefg
52 assert response.json() == {"filename": "test.txt"} 1abcdefg
54 assert testing_file_store 1abcdefg
55 assert testing_file_store[0].file.closed 1abcdefg
58# For UploadFile coverage, segments copied from Starlette tests
61@pytest.mark.anyio 1hijklmn
62async def test_upload_file(): 1hijklmn
63 stream = io.BytesIO(b"data") 1opqrstu
64 file = UploadFile(filename="file", file=stream, size=4) 1opqrstu
65 assert await file.read() == b"data" 1opqrstu
66 assert file.size == 4 1opqrstu
67 await file.write(b" and more data!") 1opqrstu
68 assert await file.read() == b"" 1opqrstu
69 assert file.size == 19 1opqrstu
70 await file.seek(0) 1opqrstu
71 assert await file.read() == b"data and more data!" 1opqrstu
72 await file.close() 1opqrstu