Coverage for tests / test_datastructures.py: 100%

47 statements  

« prev     ^ index     » next       coverage.py v7.13.3, created at 2026-02-12 18:15 +0000

1import io 1defg

2from pathlib import Path 1defg

3 

4import pytest 1defg

5from fastapi import FastAPI, UploadFile 1defg

6from fastapi.datastructures import Default 1defg

7from fastapi.testclient import TestClient 1defg

8 

9 

10def test_upload_file_invalid_pydantic_v2(): 1defg

11 with pytest.raises(ValueError): 1qrs

12 UploadFile._validate("not a Starlette UploadFile", {}) 1qrs

13 

14 

15def test_default_placeholder_equals(): 1defg

16 placeholder_1 = Default("a") 1klm

17 placeholder_2 = Default("a") 1klm

18 assert placeholder_1 == placeholder_2 1klm

19 assert placeholder_1.value == placeholder_2.value 1klm

20 

21 

22def test_default_placeholder_bool(): 1defg

23 placeholder_a = Default("a") 1nop

24 placeholder_b = Default("") 1nop

25 assert placeholder_a 1nop

26 assert not placeholder_b 1nop

27 

28 

29def test_upload_file_is_closed(tmp_path: Path): 1defg

30 path = tmp_path / "test.txt" 1abc

31 path.write_bytes(b"<file content>") 1abc

32 app = FastAPI() 1abc

33 

34 testing_file_store: list[UploadFile] = [] 1abc

35 

36 @app.post("/uploadfile/") 1abc

37 def create_upload_file(file: UploadFile): 1abc

38 testing_file_store.append(file) 1abc

39 return {"filename": file.filename} 1abc

40 

41 client = TestClient(app) 1abc

42 with path.open("rb") as file: 1abc

43 response = client.post("/uploadfile/", files={"file": file}) 1abc

44 assert response.status_code == 200, response.text 1abc

45 assert response.json() == {"filename": "test.txt"} 1abc

46 

47 assert testing_file_store 1abc

48 assert testing_file_store[0].file.closed 1abc

49 

50 

51# For UploadFile coverage, segments copied from Starlette tests 

52 

53 

54@pytest.mark.anyio 1defg

55async def test_upload_file(): 1defg

56 stream = io.BytesIO(b"data") 1hij

57 file = UploadFile(filename="file", file=stream, size=4) 1hij

58 assert await file.read() == b"data" 1hij

59 assert file.size == 4 1hij

60 await file.write(b" and more data!") 1hij

61 assert await file.read() == b"" 1hij

62 assert file.size == 19 1hij

63 await file.seek(0) 1hij

64 assert await file.read() == b"data and more data!" 1hij

65 await file.close() 1hij