| 1 |
import io |
| 2 |
from pathlib import Path |
| 3 |
from typing import cast |
| 4 |
|
| 5 |
import pytest |
| 6 |
from fastapi import FastAPI, UploadFile |
| 7 |
from fastapi.datastructures import Default, DefaultPlaceholder |
| 8 |
from fastapi.testclient import TestClient |
| 9 |
|
| 10 |
|
| 11 |
def test_upload_file_invalid_pydantic_v2(): |
| 12 |
with pytest.raises(ValueError): |
| 13 |
UploadFile._validate("not a Starlette UploadFile", {}) |
| 14 |
|
| 15 |
|
| 16 |
def test_default_placeholder_equals(): |
| 17 |
placeholder_1 = cast(DefaultPlaceholder, Default("a")) |
| 18 |
placeholder_2 = cast(DefaultPlaceholder, Default("a")) |
| 19 |
assert placeholder_1 == placeholder_2 |
| 20 |
assert placeholder_1.value == placeholder_2.value |
| 21 |
|
| 22 |
|
| 23 |
def test_default_placeholder_bool(): |
| 24 |
placeholder_a = Default("a") |
| 25 |
placeholder_b = Default("") |
| 26 |
assert placeholder_a |
| 27 |
assert not placeholder_b |
| 28 |
|
| 29 |
|
| 30 |
def test_upload_file_is_closed(tmp_path: Path): |
| 31 |
path = tmp_path / "test.txt" |
| 32 |
path.write_bytes(b"<file content>") |
| 33 |
app = FastAPI() |
| 34 |
|
| 35 |
testing_file_store: list[UploadFile] = [] |
| 36 |
|
| 37 |
@app.post("/uploadfile/") |
| 38 |
def create_upload_file(file: UploadFile): |
| 39 |
testing_file_store.append(file) |
| 40 |
return {"filename": file.filename} |
| 41 |
|
| 42 |
client = TestClient(app) |
| 43 |
with path.open("rb") as file: |
| 44 |
response = client.post("/uploadfile/", files={"file": file}) |
| 45 |
assert response.status_code == 200, response.text |
| 46 |
assert response.json() == {"filename": "test.txt"} |
| 47 |
|
| 48 |
assert testing_file_store |
| 49 |
assert testing_file_store[0].file.closed |
| 50 |
|
| 51 |
|
| 52 |
# For UploadFile coverage, segments copied from Starlette tests |
| 53 |
|
| 54 |
|
| 55 |
@pytest.mark.anyio |
| 56 |
async def test_upload_file(): |
| 57 |
stream = io.BytesIO(b"data") |
| 58 |
file = UploadFile(filename="file", file=stream, size=4) |
| 59 |
assert await file.read() == b"data" |
| 60 |
assert file.size == 4 |
| 61 |
await file.write(b" and more data!") |
| 62 |
assert await file.read() == b"" |
| 63 |
assert file.size == 19 |
| 64 |
await file.seek(0) |
| 65 |
assert await file.read() == b"data and more data!" |
| 66 |
await file.close() |