Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
222 lines
9.3 KiB
Python
222 lines
9.3 KiB
Python
"""Пробный доступ новым пользователям (решение Хозяина 01.10.2026).
|
|
|
|
Новая учётка — один диалог и пять вопросов на всё время. Прежние учётки не задеты;
|
|
админ и владелец под пробный режим не попадают никогда.
|
|
"""
|
|
|
|
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"
|
|
|
|
|
|
@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.setenv("TRIAL_QUESTIONS", "5")
|
|
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")
|
|
res = auth.register_user(NEW, "Пароль-надёжный-123", "")
|
|
assert res.get("ok"), res
|
|
from fastapi.testclient import TestClient
|
|
return db, auth, main, TestClient(main.app)
|
|
|
|
|
|
def _h(auth, user, tab, role="user"):
|
|
return {"Authorization": "Bearer " + auth._make_token(user, role), "X-Tab-Id": tab}
|
|
|
|
|
|
def _asked(db, user, n):
|
|
for _ in range(n):
|
|
db.log_action(user, "chat", "POST", "/api/chat", None, None, 200)
|
|
|
|
|
|
def _first_dialog(db, user, tab="t-first"):
|
|
db.save_message(user, tab, "user", "первый вопрос")
|
|
return tab
|
|
|
|
|
|
# --- кто пробный ---
|
|
|
|
def test_registration_marks_new_user_as_trial(env):
|
|
db, auth, main, client = env
|
|
assert db.get_user_by_email(NEW)["trial"] == 1
|
|
assert db.get_user_by_email(OLD)["trial"] == 0
|
|
|
|
|
|
def test_admin_and_owner_never_trial(env, monkeypatch):
|
|
db, auth, main, client = env
|
|
db.set_trial(OLD, True)
|
|
db.set_user_role(OLD, "admin")
|
|
assert main._trial_state(OLD) is None
|
|
monkeypatch.setenv("AGENT_OWNER_EMAILS", NEW)
|
|
assert main._trial_state(NEW) is None
|
|
|
|
|
|
# --- пять вопросов ---
|
|
|
|
def test_fifth_question_allowed_sixth_refused(env):
|
|
db, auth, main, client = env
|
|
tab = _first_dialog(db, NEW)
|
|
_asked(db, NEW, 4)
|
|
main._refuse_if_trial_over(NEW) # пятый ещё можно
|
|
_asked(db, NEW, 1)
|
|
r = client.post("/api/chat", headers=_h(auth, NEW, tab), json={"message": "ещё", "tab_id": tab})
|
|
assert r.status_code == 402
|
|
assert "Пробный доступ закончился" in r.json()["detail"]
|
|
assert "все 5 вопросов заданы" in r.json()["detail"]
|
|
|
|
|
|
def test_old_user_not_limited_by_trial(env):
|
|
db, auth, main, client = env
|
|
_asked(db, OLD, 50)
|
|
main._refuse_if_trial_over(OLD) # не бросает
|
|
assert main._trial_state(OLD) is None
|
|
|
|
|
|
def test_trial_over_blocks_uploads_and_demo(env):
|
|
db, auth, main, client = env
|
|
tab = _first_dialog(db, NEW)
|
|
_asked(db, NEW, 5)
|
|
h = _h(auth, NEW, tab)
|
|
r = client.post("/api/upload", headers=h, files={"file": ("a.xlsx", b"x" * 10, "application/octet-stream")})
|
|
assert r.status_code == 402
|
|
assert client.post("/api/demo-file", headers=h, json={"tab_id": tab}).status_code == 402
|
|
|
|
|
|
# --- один диалог ---
|
|
|
|
def test_question_from_other_dialog_redirected_to_trial_dialog(env):
|
|
db, auth, main, client = env
|
|
tab = _first_dialog(db, NEW)
|
|
r = client.post("/api/chat", headers=_h(auth, NEW, "t-second"),
|
|
json={"message": "вопрос", "tab_id": "t-second"})
|
|
assert r.status_code == 409
|
|
assert r.json()["trial_tab"] == tab
|
|
assert not [s for s in db.list_sessions(NEW) if s["tab_id"] == "t-second"]
|
|
|
|
|
|
def test_first_write_defines_the_dialog(env):
|
|
db, auth, main, client = env
|
|
assert main._trial_state(NEW)["tab"] is None # ещё ни одного диалога
|
|
r = client.post("/api/upload", headers=_h(auth, NEW, "t-a"),
|
|
files={"file": ("a.xlsx", b"x" * 10, "application/octet-stream")})
|
|
assert r.status_code == 200
|
|
assert main._trial_state(NEW)["tab"] == "t-a"
|
|
|
|
|
|
def test_upload_demo_date_into_other_dialog_refused(env):
|
|
db, auth, main, client = env
|
|
_first_dialog(db, NEW)
|
|
h = _h(auth, NEW, "t-second")
|
|
r = client.post("/api/upload", headers=h, files={"file": ("a.xlsx", b"x" * 10, "application/octet-stream")})
|
|
assert r.status_code == 403 and "один диалог" in r.json()["detail"]
|
|
assert client.post("/api/demo-file", headers=h, json={"tab_id": "t-second"}).status_code == 403
|
|
r = client.post("/api/sessions/t-second/date", headers=h, json={"date": "2026-01-01"})
|
|
assert r.status_code == 403
|
|
meta = "filename {},tab_id {}".format(base64.b64encode(b"a.pdf").decode(),
|
|
base64.b64encode(b"t-second").decode())
|
|
r = client.post("/api/tus", headers={**h, "Tus-Resumable": "1.0.0", "Upload-Length": "10",
|
|
"Upload-Metadata": meta})
|
|
assert r.status_code == 403
|
|
|
|
|
|
def test_old_user_can_open_many_dialogs(env):
|
|
db, auth, main, client = env
|
|
_first_dialog(db, OLD)
|
|
r = client.post("/api/upload", headers=_h(auth, OLD, "t-second"),
|
|
files={"file": ("a.xlsx", b"x" * 10, "application/octet-stream")})
|
|
assert r.status_code == 200
|
|
|
|
|
|
# --- что видит человек ---
|
|
|
|
def test_limits_report_trial(env):
|
|
db, auth, main, client = 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, "files_at_once": 2, "tab": "t-first"}
|
|
d = client.get("/api/limits", headers=_h(auth, OLD, "x")).json()
|
|
assert "trial" not in d
|
|
|
|
|
|
def test_page_handles_trial():
|
|
html = open(os.path.join(ROOT, "static", "chat.html"), encoding="utf-8").read()
|
|
assert "if (b.trial) {" in html # значок
|
|
assert "d.trial_tab" in html # переход в пробный диалог и повтор
|
|
assert "function applyTrial()" in html # прячет «Новый чат», открывает диалог
|
|
# в обе стороны и при выходе — иначе следующий вошедший остался бы без «Нового чата»
|
|
assert "b.style.display = t ? 'none' : ''" in html
|
|
assert "lastBalance = null; applyTrial();" in html
|
|
# запрета в самой функции нового чата нет: удаление единственного диалога открывает пустой
|
|
i = html.index("async function newChat() {")
|
|
assert "trial" not in html[i:i + 200]
|
|
assert "if (tabId !== d.trial_tab) return;" in html
|
|
|
|
|
|
# --- админка ---
|
|
|
|
def test_admin_toggles_trial_and_sees_count(env):
|
|
db, auth, main, client = env
|
|
db.create_user("boss@x", "h", role="admin")
|
|
ah = _h(auth, "boss@x", "x", "admin")
|
|
_asked(db, NEW, 3)
|
|
rows = client.get("/api/admin/users", headers=ah).json()
|
|
rows = rows["users"] if isinstance(rows, dict) else rows
|
|
me = [u for u in rows if u["email"] == NEW][0]
|
|
assert me["trial"] == 1 and me["trial_used"] == 3
|
|
r = client.post("/api/admin/users/trial", headers=ah, json={"email": NEW, "trial": False})
|
|
assert r.status_code == 200
|
|
assert db.get_user_by_email(NEW)["trial"] == 0
|
|
r = client.post("/api/admin/users/trial", headers=ah, json={"email": NEW, "trial": "no"})
|
|
assert r.status_code == 400
|
|
r = client.post("/api/admin/users/trial", headers=ah, json={"email": "nobody@x", "trial": True})
|
|
assert r.status_code == 404
|
|
r = client.post("/api/admin/users/trial", headers=_h(auth, NEW, "x"), json={"email": NEW, "trial": False})
|
|
assert r.status_code == 403
|
|
|
|
|
|
def test_stream_balance_event_uses_same_view():
|
|
# Событие остатка после ответа обязано нести пробный режим, иначе значок после первого же
|
|
# ответа вернулся бы к суточному остатку.
|
|
src = open(os.path.join(ROOT, "main.py"), encoding="utf-8").read()
|
|
assert "_balance = await asyncio.to_thread(_person_view, user)" in src
|
|
assert "quotas.person_snapshot, user)" not in src
|
|
|
|
|
|
def test_first_dialog_is_the_earliest(env):
|
|
# Если в базе у человека окажутся записи в двух диалогах (например, пробный режим
|
|
# включили уже работавшему), его диалог — самый первый, а не последний.
|
|
db, auth, main, client = env
|
|
db.save_message(NEW, "t-early", "user", "раз")
|
|
db.save_message(NEW, "t-late", "user", "два")
|
|
assert db.first_dialog(NEW) == "t-early"
|
|
|
|
|
|
def test_deleting_the_dialog_frees_one_slot_but_keeps_the_count(env):
|
|
db, auth, main, client = env
|
|
tab = _first_dialog(db, NEW)
|
|
_asked(db, NEW, 3)
|
|
assert client.delete(f"/api/sessions/{tab}", headers=_h(auth, NEW, tab)).status_code == 200
|
|
st = main._trial_state(NEW)
|
|
assert st["tab"] is None and st["used"] == 3 # новый диалог можно, вопросы не вернулись
|