"""Yükleme uçları testleri: python3 tests/test_uploads_api.py""" import io import os import tempfile import time import zipfile from pathlib import Path os.environ["PACKER_PASSWORD"] = "pw" os.environ.setdefault("PORTER_DATA_DIR", tempfile.mkdtemp()) from _t import run # noqa: E402 from fastapi.testclient import TestClient # noqa: E402 import app as app_mod # noqa: E402 import upload_cache # noqa: E402 from build_pipeline import BuildResult # noqa: E402 client = TestClient(app_mod.app) PW = {"build_password": "pw"} HDR = {"X-Build-Password": "pw"} def _fresh_cache(): cache = upload_cache.UploadCache(Path(tempfile.mkdtemp())) cache.free_bytes = lambda: 10 ** 12 app_mod.UPLOADS = cache return cache def _zip_bytes(extra: str = "") -> bytes: buf = io.BytesIO() with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as zf: zf.writestr("www/index.html", "Oyun" + extra + "x" * 4000) return buf.getvalue() def _upload(data: bytes, password: str = "pw"): return client.post( "/api/uploads", files={"www_zip": ("oyun.zip", data, "application/zip")}, data={"build_password": password}, ) def test_upload_requires_password(): _fresh_cache() assert _upload(_zip_bytes(), password="").status_code == 403 assert _upload(_zip_bytes(), password="yanlis").status_code == 403 r = _upload(_zip_bytes()) assert r.status_code == 200, r.text assert r.json()["upload"]["id"] def test_list_and_delete(): _fresh_cache() uid = _upload(_zip_bytes()).json()["upload"]["id"] assert client.get("/api/uploads").status_code == 403 # The password travels in a header: a query string ends up in access logs. assert client.get("/api/uploads", params=PW).status_code == 403 listed = client.get("/api/uploads", headers=HDR).json() assert [u["id"] for u in listed["uploads"]] == [uid] assert "free_bytes" in listed and "total_bytes" in listed and "persistent" in listed assert client.delete(f"/api/uploads/{uid}").status_code == 403 assert client.delete(f"/api/uploads/{uid}", params=PW).status_code == 403 assert client.delete(f"/api/uploads/{uid}", headers=HDR).status_code == 200 assert client.get("/api/uploads", headers=HDR).json()["uploads"] == [] assert client.delete(f"/api/uploads/{uid}", headers=HDR).status_code == 404 def test_frontend_never_puts_password_in_url(): from _t import ROOT js = (ROOT / "static/app.js").read_text() assert "build_password=" not in js assert "X-Build-Password" in js def test_corrupt_zip_rejected(): cache = _fresh_cache() r = _upload(_zip_bytes()[:-100]) assert r.status_code == 400, r.text assert cache.list() == [] def _wait(build_id: str) -> None: for _ in range(100): with app_mod._builds_lock: if app_mod._builds[build_id].status != "running": return time.sleep(0.05) raise AssertionError("derleme bitmedi") def test_build_with_cached_id_keeps_zip(): cache = _fresh_cache() uid = _upload(_zip_bytes()).json()["upload"]["id"] seen = {} def fake_run_build(req, log_callback=None): seen["path"] = req.www_zip_path return BuildResult(success=False, apk_path=None, log_tail="", error_message="sahte") original = app_mod.run_build app_mod.run_build = fake_run_build try: r = client.post("/api/build", data={"cached_zip_id": uid, **PW}) assert r.status_code == 200, r.text _wait(r.json()["build_id"]) finally: app_mod.run_build = original assert seen["path"] == str(cache.path_of(uid)) assert cache.path_of(uid).is_file() assert cache.get(uid).active == 0 def test_build_with_direct_zip_is_stored(): cache = _fresh_cache() original = app_mod.run_build app_mod.run_build = lambda req, log_callback=None: BuildResult(False, None, "", "sahte") try: r = client.post( "/api/build", files={"www_zip": ("oyun.zip", _zip_bytes(), "application/zip")}, data=PW, ) assert r.status_code == 200, r.text _wait(r.json()["build_id"]) finally: app_mod.run_build = original assert len(cache.list()) == 1 def test_build_unknown_cached_id_410(): _fresh_cache() r = client.post("/api/build", data={"cached_zip_id": "0123456789abcdef", **PW}) assert r.status_code == 410, r.text def test_build_without_zip_400(): _fresh_cache() r = client.post("/api/build", data=PW) assert r.status_code == 400, r.text assert "listeden" in r.json()["detail"] def test_invalid_size_mode_rejected(): cache = _fresh_cache() uid = _upload(_zip_bytes()).json()["upload"]["id"] r = client.post("/api/build", data={"cached_zip_id": uid, "optimize_images": "max", **PW}) assert r.status_code == 400, r.text assert cache.get(uid).active == 0 def test_delete_in_use_refused(): cache = _fresh_cache() uid = _upload(_zip_bytes()).json()["upload"]["id"] cache.acquire(uid) r = client.delete(f"/api/uploads/{uid}", headers=HDR) assert r.status_code == 409, r.text assert "derleme" in r.json()["detail"] cache.release(uid) def test_trim_keeps_only_apk(): root = Path(tempfile.mkdtemp()) work = root / "build-1" apk = work / "app/build/outputs/apk/release/app-release.apk" apk.parent.mkdir(parents=True) apk.write_bytes(b"APK") www = work / "app/src/main/assets/www" www.mkdir(parents=True) (www / "a.png").write_bytes(b"x") kept = Path(app_mod._remember_and_trim_build_dir(str(apk))) assert kept.read_bytes() == b"APK" assert kept.parent == work assert sorted(p.name for p in work.iterdir()) == ["app-release.apk"] def test_inject_reads_local_copy(): import build_pipeline as bp import zipcheck as zc src = Path(tempfile.mkdtemp()) / "oyun.zip" src.write_bytes(_zip_bytes()) work = Path(tempfile.mkdtemp()) copies = [] original = zc.yerel_kopya def spy(kaynak, hedef, beklenen_sha=""): copies.append(Path(hedef)) return original(kaynak, hedef, beklenen_sha) zc.yerel_kopya = spy try: ok, msg = bp._inject_www(work, str(src)) finally: zc.yerel_kopya = original assert ok, msg assert (work / "app/src/main/assets/www/index.html").is_file() assert copies and copies[0] != src and not copies[0].exists() def test_inject_reports_unreadable_store(): import build_pipeline as bp import zipcheck as zc original = zc.yerel_kopya zc.yerel_kopya = lambda kaynak, hedef, beklenen_sha="": zc.KopyaSonuc(ok=False, hata="G/Ç hatası") try: ok, msg = bp._inject_www(Path(tempfile.mkdtemp()), "/yok/oyun.zip") finally: zc.yerel_kopya = original assert not ok assert msg.startswith("Oyun dosyası depodan okunamadı") and "G/Ç hatası" in msg, msg def test_upload_checks_run_off_the_event_loop(): """Hashing/inspecting a 1.5 GB zip must not freeze the server (SSE logs, lists).""" import asyncio cache = _fresh_cache() on_loop = {} def runs_on_loop() -> bool: try: asyncio.get_running_loop() return True except RuntimeError: return False real_check, real_commit = app_mod._check_stored, cache.commit def check(entry): on_loop["check"] = runs_on_loop() return real_check(entry) def commit(*a, **k): on_loop["commit"] = runs_on_loop() return real_commit(*a, **k) app_mod._check_stored, cache.commit = check, commit try: assert _upload(_zip_bytes()).status_code == 200 finally: app_mod._check_stored = real_check assert on_loop == {"check": False, "commit": False}, on_loop def test_trim_happens_outside_the_builds_lock(): """Deleting gigabytes of build output must not hold the lock SSE needs.""" cache = _fresh_cache() uid = _upload(_zip_bytes()).json()["upload"]["id"] held = {} real_trim, real_run = app_mod._remember_and_trim_build_dir, app_mod.run_build def trim(apk_path): held["locked"] = app_mod._builds_lock.locked() return apk_path app_mod._remember_and_trim_build_dir = trim app_mod.run_build = lambda req, log_callback=None: BuildResult( success=True, apk_path="/tmp/x.apk", log_tail="", error_message=None) try: r = client.post("/api/build", data={**PW, "cached_zip_id": uid, "app_name": "Oyun", "build_variant": "debug"}) assert r.status_code == 200, r.text _wait(r.json()["build_id"]) finally: app_mod._remember_and_trim_build_dir, app_mod.run_build = real_trim, real_run assert held == {"locked": False} with app_mod._builds_lock: state = app_mod._builds[r.json()["build_id"]] assert state.status == "success" and state.apk_path == "/tmp/x.apk" def test_failed_build_removes_its_work_dir(): import glob import build_pipeline pattern = str(Path(tempfile.gettempdir()) / "riaslink-build-*") before = set(glob.glob(pattern)) req = build_pipeline.BuildRequest( www_zip_path="/yok/oyun.zip", app_name="Oyun", application_id="fun.riaslink.test", version_name="1.0", version_code=1, fps_default_visible=False, accent_hex="#ffffff", build_variant="debug", aerokey_enabled=False, ) result = build_pipeline.run_build(req) assert not result.success assert set(glob.glob(pattern)) - before == set() if __name__ == "__main__": run(globals())