cmvr-visual/backend/tests/test_upload_guard.py

77 lines
2.4 KiB
Python
Raw Permalink Normal View History

import httpx
import asyncio
from types import SimpleNamespace
async def test_unauthenticated_upload_does_not_consume_or_parse_body(system):
consumed = []
async def body():
consumed.append(True)
yield b"x" * 1024
async with httpx.AsyncClient(
transport=httpx.ASGITransport(app=system.app), base_url="http://test"
) as client:
response = await client.post(
"/api/assets",
content=body(),
headers={"Content-Type": "multipart/form-data; boundary=test"},
)
assert response.status_code == 401
assert consumed == []
async def test_chunked_upload_is_bounded_before_multipart_parser(system, monkeypatch):
from starlette.requests import Request
called = []
original = Request._get_form
async def form(self, *args, **kwargs):
called.append(True)
return await original(self, *args, **kwargs)
monkeypatch.setattr(Request, "_get_form", form)
system.settings.max_upload_bytes = 16
async def body():
for _ in range(18):
yield b"x" * (64 * 1024)
response = await system.client.post(
"/api/assets",
content=body(),
headers={"Content-Type": "multipart/form-data; boundary=test"},
)
assert response.status_code == 413
assert called == []
assert list((system.settings.asset_root.parent / "tmp").glob("*")) == []
async def test_two_owners_share_reserved_upload_capacity(system, other_client, monkeypatch):
system.settings.mode = "production"
system.settings.max_data_bytes = 127
system.settings.min_free_bytes = 0
monkeypatch.setattr(
"app.services.quotas.shutil.disk_usage", lambda _: SimpleNamespace(total=1000, free=1000)
)
entered, release = asyncio.Event(), asyncio.Event()
async def held():
entered.set()
await release.wait()
yield b"x" * 32
headers = {"Content-Type": "multipart/form-data; boundary=test", "Content-Length": "32"}
first = asyncio.create_task(system.client.post("/api/assets", content=held(), headers=headers))
try:
await asyncio.wait_for(entered.wait(), 2)
second = await other_client.post("/api/assets", content=b"x" * 32, headers=headers)
assert (
second.status_code == 503 and second.json()["detail"]["code"] == "storage_insufficient"
)
finally:
release.set()
await first