Coverage for tests/test_datastructures.py: 100%

51 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-09-06 16:22 +0000

1import io 1fghij

2from pathlib import Path 1fghij

3from typing import List 1fghij

4 

5import pytest 1fghij

6from fastapi import FastAPI, UploadFile 1fghij

7from fastapi.datastructures import Default 1fghij

8from fastapi.testclient import TestClient 1fghij

9 

10 

11# TODO: remove when deprecating Pydantic v1 

12def test_upload_file_invalid(): 1fghij

13 with pytest.raises(ValueError): 1zABCD

14 UploadFile.validate("not a Starlette UploadFile") 1zABCD

15 

16 

17def test_upload_file_invalid_pydantic_v2(): 1fghij

18 with pytest.raises(ValueError): 1EFGHI

19 UploadFile._validate("not a Starlette UploadFile", {}) 1EFGHI

20 

21 

22def test_default_placeholder_equals(): 1fghij

23 placeholder_1 = Default("a") 1pqrst

24 placeholder_2 = Default("a") 1pqrst

25 assert placeholder_1 == placeholder_2 1pqrst

26 assert placeholder_1.value == placeholder_2.value 1pqrst

27 

28 

29def test_default_placeholder_bool(): 1fghij

30 placeholder_a = Default("a") 1uvwxy

31 placeholder_b = Default("") 1uvwxy

32 assert placeholder_a 1uvwxy

33 assert not placeholder_b 1uvwxy

34 

35 

36def test_upload_file_is_closed(tmp_path: Path): 1fghij

37 path = tmp_path / "test.txt" 1abcde

38 path.write_bytes(b"<file content>") 1abcde

39 app = FastAPI() 1abcde

40 

41 testing_file_store: List[UploadFile] = [] 1abcde

42 

43 @app.post("/uploadfile/") 1abcde

44 def create_upload_file(file: UploadFile): 1abcde

45 testing_file_store.append(file) 1abcde

46 return {"filename": file.filename} 1abcde

47 

48 client = TestClient(app) 1abcde

49 with path.open("rb") as file: 1abcde

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

51 assert response.status_code == 200, response.text 1abcde

52 assert response.json() == {"filename": "test.txt"} 1abcde

53 

54 assert testing_file_store 1abcde

55 assert testing_file_store[0].file.closed 1abcde

56 

57 

58# For UploadFile coverage, segments copied from Starlette tests 

59 

60 

61@pytest.mark.anyio 1fghij

62async def test_upload_file(): 1fghij

63 stream = io.BytesIO(b"data") 1klmno

64 file = UploadFile(filename="file", file=stream, size=4) 1klmno

65 assert await file.read() == b"data" 1klmno

66 assert file.size == 4 1klmno

67 await file.write(b" and more data!") 1klmno

68 assert await file.read() == b"" 1klmno

69 assert file.size == 19 1klmno

70 await file.seek(0) 1klmno

71 assert await file.read() == b"data and more data!" 1klmno

72 await file.close() 1klmno