test: пробный доступ — не больше двух файлов за раз (красные)
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -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
|
||||
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user