File size: 9,627 Bytes
f20b6e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67e71f2
f20b6e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67e71f2
 
 
f20b6e7
 
 
67e71f2
 
 
 
 
 
 
 
 
 
 
 
f20b6e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67e71f2
f20b6e7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67e71f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f20b6e7
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""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", "<title>Oyun</title>" + 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())