Coverage for tests/test_datastructures.py: 100%

51 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1import io 1abcde

2from pathlib import Path 1abcde

3from typing import List 1abcde

4 

5import pytest 1abcde

6from fastapi import FastAPI, UploadFile 1abcde

7from fastapi.datastructures import Default 1abcde

8from fastapi.testclient import TestClient 1abcde

9 

10 

11# TODO: remove when deprecating Pydantic v1 

12def test_upload_file_invalid(): 1abcde

13 with pytest.raises(ValueError): 1abcde

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

15 

16 

17def test_upload_file_invalid_pydantic_v2(): 1abcde

18 with pytest.raises(ValueError): 1abcde

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

20 

21 

22def test_default_placeholder_equals(): 1abcde

23 placeholder_1 = Default("a") 1abcde

24 placeholder_2 = Default("a") 1abcde

25 assert placeholder_1 == placeholder_2 1abcde

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

27 

28 

29def test_default_placeholder_bool(): 1abcde

30 placeholder_a = Default("a") 1abcde

31 placeholder_b = Default("") 1abcde

32 assert placeholder_a 1abcde

33 assert not placeholder_b 1abcde

34 

35 

36def test_upload_file_is_closed(tmp_path: Path): 1abcde

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 1abcde

62async def test_upload_file(): 1abcde

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

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

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

66 assert file.size == 4 1abcde

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

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

69 assert file.size == 19 1abcde

70 await file.seek(0) 1abcde

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

72 await file.close() 1abcde