From 059b40fdb2e58fe5ccb71da9b5024dd9fd15a5e6 Mon Sep 17 00:00:00 2001 From: anor Date: Thu, 1 Oct 2026 20:12:03 +1000 Subject: [PATCH] =?UTF-8?q?test:=20=D0=BF=D1=80=D0=BE=D0=B1=D0=BD=D1=8B?= =?UTF-8?q?=D0=B9=20=D0=B4=D0=BE=D1=81=D1=82=D1=83=D0=BF=20=E2=80=94=20?= =?UTF-8?q?=D0=BD=D0=B5=20=D0=B1=D0=BE=D0=BB=D1=8C=D1=88=D0=B5=20=D0=B4?= =?UTF-8?q?=D0=B2=D1=83=D1=85=20=D1=84=D0=B0=D0=B9=D0=BB=D0=BE=D0=B2=20?= =?UTF-8?q?=D0=B7=D0=B0=20=D1=80=D0=B0=D0=B7=20(=D0=BA=D1=80=D0=B0=D1=81?= =?UTF-8?q?=D0=BD=D1=8B=D0=B5)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 (1M context) --- tests/test_trial_access.py | 2 +- tests/test_trial_files.py | 132 +++++++++++++++++++++++++++++++++++++ 2 files changed, 133 insertions(+), 1 deletion(-) create mode 100644 tests/test_trial_files.py diff --git a/tests/test_trial_access.py b/tests/test_trial_access.py index 0bbc832..2dbcf29 100644 --- a/tests/test_trial_access.py +++ b/tests/test_trial_access.py @@ -154,7 +154,7 @@ def test_limits_report_trial(env): _first_dialog(db, NEW) _asked(db, NEW, 2) d = client.get("/api/limits", headers=_h(auth, NEW, "t-first")).json() - assert d["trial"] == {"used": 2, "limit": 5, "tab": "t-first"} + assert d["trial"] == {"used": 2, "limit": 5, "files_at_once": 2, "tab": "t-first"} d = client.get("/api/limits", headers=_h(auth, OLD, "x")).json() assert "trial" not in d diff --git a/tests/test_trial_files.py b/tests/test_trial_files.py new file mode 100644 index 0000000..9b89585 --- /dev/null +++ b/tests/test_trial_files.py @@ -0,0 +1,132 @@ +"""Пробный доступ: не больше двух файлов за раз (распоряжение Хозяина 01.10.2026). + +«За раз» — между двумя вопросами: человек прикладывает файлы и задаёт вопрос; после вопроса +можно приложить ещё. Предел держит сервер (обе двери загрузки: /api/upload и tus, включая +параллельно созданные загрузки), страница лишь не даёт выбрать лишнее. + +Red-green: написано ДО кода. +""" +import base64 +import importlib +import os +import sys + +import pytest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +if ROOT not in sys.path: + sys.path.insert(0, ROOT) + +NEW = "novichok@x" +OLD = "stary@x" +TAB = "t-first" + + +@pytest.fixture() +def env(tmp_path, monkeypatch): + monkeypatch.setenv("DB_PATH", str(tmp_path / "t.db")) + monkeypatch.setenv("DATA_DIR", str(tmp_path / "data")) + monkeypatch.setenv("AI_BACKEND", "claude") + monkeypatch.setenv("SESSION_SECRET", "test-secret") + monkeypatch.delenv("TRIAL_FILES_AT_ONCE", raising=False) + monkeypatch.delenv("AGENT_OWNER_EMAILS", raising=False) + monkeypatch.delenv("SMTP_HOST", raising=False) + monkeypatch.chdir(ROOT) + import db, auth, claude_bridge, quotas, main + for m in (db, auth, claude_bridge, quotas, main): + importlib.reload(m) + db.init_db() + db.create_user(OLD, "h") + assert auth.register_user(NEW, "Пароль-надёжный-123", "").get("ok") + from fastapi.testclient import TestClient + return db, auth, main, TestClient(main.app) + + +def _h(auth, user): + return {"Authorization": "Bearer " + auth._make_token(user, "user"), "X-Tab-Id": TAB} + + +def _up(client, auth, user, name): + return client.post("/api/upload", headers=_h(auth, user), + files={"file": (name, b"x" * 10, "application/octet-stream")}) + + +def _tus(client, auth, user, name): + meta = "filename {},tab_id {}".format(base64.b64encode(name.encode()).decode(), + base64.b64encode(TAB.encode()).decode()) + return client.post("/api/tus", headers={**_h(auth, user), "Tus-Resumable": "1.0.0", + "Upload-Length": "10", "Upload-Metadata": meta}) + + +def test_third_file_before_question_refused(env): + """Порча: не считать загрузки после последнего вопроса → третий принят.""" + db, auth, main, client = env + assert _up(client, auth, NEW, "a.xlsx").status_code == 200 + assert _up(client, auth, NEW, "b.xlsx").status_code == 200 + r = _up(client, auth, NEW, "c.xlsx") + assert r.status_code == 403 + assert "2 файл" in r.json()["detail"] + + +def test_after_question_two_more_allowed(env): + """После вопроса — снова два. Порча: считать загрузки за всё время → отказ.""" + db, auth, main, client = env + _up(client, auth, NEW, "a.xlsx") + _up(client, auth, NEW, "b.xlsx") + import time + time.sleep(0.01) + db.log_action(NEW, "chat", "POST", "/api/chat", f"tab={TAB} | вопрос", None, 200) + time.sleep(0.01) + assert _up(client, auth, NEW, "c.xlsx").status_code == 200 + assert _up(client, auth, NEW, "d.xlsx").status_code == 200 + assert _up(client, auth, NEW, "e.xlsx").status_code == 403 + + +def test_parallel_tus_creations_counted(env): + """Три загрузки, созданные разом (ни одна ещё не завершена), — третья отвергнута. + Порча: не считать идущие загрузки → все три приняты.""" + db, auth, main, client = env + assert _tus(client, auth, NEW, "a.xlsx").status_code == 201 + assert _tus(client, auth, NEW, "b.xlsx").status_code == 201 + assert _tus(client, auth, NEW, "c.xlsx").status_code == 403 + + +def test_regular_user_not_limited(env): + """Обычный человек — без этого предела. Порча: проверять всех → отказ.""" + db, auth, main, client = env + for n in "abc": + assert _up(client, auth, OLD, n + ".xlsx").status_code == 200 + + +def test_trial_state_tells_page_the_limit(env): + """Страница узнаёт предел из снимка остатка — без второй константы в разметке.""" + db, auth, main, client = env + lim = client.get("/api/limits", headers=_h(auth, NEW)).json() + assert lim["trial"]["files_at_once"] == 2 + + +def test_chat_page_keeps_at_most_limit_files(): + html = open(os.path.join(ROOT, "static", "chat.html"), encoding="utf-8").read() + fn = html[html.index("function handleFiles"):html.index("function renderFileList")] + assert "files_at_once" in fn + + +def test_inflight_plain_uploads_counted(env): + """Запасной путь /api/upload: загрузки, идущие прямо сейчас (между проверкой и записью в + журнал есть ожидание), считаются — иначе три параллельных запроса прошли бы все (зайка + 01.10.2026). Порча: не учитывать идущие → 200.""" + db, auth, main, client = env + main._inflight_uploads[(NEW, TAB)] = 2 + assert _up(client, auth, NEW, "a.xlsx").status_code == 403 + main._inflight_uploads.clear() + assert _up(client, auth, NEW, "a.xlsx").status_code == 200 + assert main._inflight_uploads.get((NEW, TAB), 0) == 0 # счётчик отпущен + + +def test_garbage_setting_does_not_disable_trial(env, monkeypatch): + """Опечатка в TRIAL_FILES_AT_ONCE не выключает пробный режим целиком: предел берётся по + умолчанию. Порча: голый int() → _trial_state None → нет ни пяти вопросов, ни одного диалога.""" + db, auth, main, client = env + monkeypatch.setenv("TRIAL_FILES_AT_ONCE", "") + st = main._trial_state(NEW) + assert st is not None and st["files_at_once"] == 2