sightbox/backend/tests/test_trial_check.py

147 lines
5.4 KiB
Python

"""
tests/test_trial_check.py — tests for the /internal/check-trial/<tenant_slug>
route. No call ever reaches a real Frappe site: billing.disable_users is
monkeypatched on the trial_check module (the name it was imported into),
and StateStore is monkeypatched to a stub so no real SQLite file is
touched — mirrors test_stripe_webhook.py's approach, since this route
shares the exact same dispatch-then-delegate shape.
"""
from datetime import datetime, timedelta, timezone
from unittest.mock import MagicMock
import pytest
import app as app_module
import billing.billing as billing
import billing.trial_check as trial_check
from billing.tenants import TenantConfig, TenantRegistry
class _StubStateStore:
"""Replaces the real StateStore so tests never touch SQLite."""
def __init__(self, tenant_slug, db_path=None):
self.tenant_slug = tenant_slug
self.db_path = db_path
def _make_tenant(trial_start_date=None, trial_days=None):
return TenantConfig(
slug="acme",
frappe_api_url="http://frappe.test",
frappe_api_key="key",
frappe_api_secret="secret",
stripe_webhook_secret="whsec_acme",
trial_start_date=trial_start_date,
trial_days=trial_days,
)
@pytest.fixture
def make_client(monkeypatch):
"""Returns a factory so each test can configure its own tenant's trial fields."""
monkeypatch.setattr(trial_check, "StateStore", _StubStateStore)
flask_app = app_module.app
flask_app.config["TESTING"] = True
def _make(tenant):
registry = TenantRegistry({"acme": tenant})
registry.frappe_client_for = MagicMock(return_value=MagicMock())
flask_app.config["TENANT_REGISTRY"] = registry
return flask_app.test_client()
return _make
def test_unknown_tenant_returns_404(make_client):
client = make_client(_make_tenant())
response = client.post("/internal/check-trial/not-a-real-tenant")
assert response.status_code == 404
assert response.get_json()["error"] == "unknown tenant"
def test_no_trial_configured_is_a_noop(make_client, monkeypatch):
disable_spy = MagicMock()
monkeypatch.setattr(trial_check, "disable_users", disable_spy)
client = make_client(_make_tenant())
response = client.post("/internal/check-trial/acme")
assert response.status_code == 200
assert response.get_json()["status"] == "no_trial_configured"
disable_spy.assert_not_called()
def test_trial_not_yet_due_is_a_noop(make_client, monkeypatch):
disable_spy = MagicMock()
monkeypatch.setattr(trial_check, "disable_users", disable_spy)
recent_start = (datetime.now(timezone.utc) - timedelta(days=2)).isoformat()
client = make_client(_make_tenant(trial_start_date=recent_start, trial_days=14))
response = client.post("/internal/check-trial/acme")
assert response.status_code == 200
assert response.get_json()["status"] == "not_due"
disable_spy.assert_not_called()
def test_expired_trial_locks_and_returns_200(make_client, monkeypatch):
disable_spy = MagicMock(return_value={"locked": ["alice"], "failed": []})
monkeypatch.setattr(trial_check, "disable_users", disable_spy)
old_start = (datetime.now(timezone.utc) - timedelta(days=30)).isoformat()
client = make_client(_make_tenant(trial_start_date=old_start, trial_days=14))
response = client.post("/internal/check-trial/acme")
assert response.status_code == 200
assert response.get_json()["status"] == "locked"
disable_spy.assert_called_once()
# the StateStore handed to disable_users was built for exactly this tenant
state_store_arg = disable_spy.call_args[0][1]
assert state_store_arg.tenant_slug == "acme"
def test_expired_trial_already_locked_reports_distinct_status(make_client, monkeypatch):
# A repeat daily-scheduler tick after everyone's already locked: disable_users()
# correctly finds nothing newly eligible (see billing.py) and no-ops.
disable_spy = MagicMock(return_value={"locked": [], "failed": []})
monkeypatch.setattr(trial_check, "disable_users", disable_spy)
old_start = (datetime.now(timezone.utc) - timedelta(days=30)).isoformat()
client = make_client(_make_tenant(trial_start_date=old_start, trial_days=14))
response = client.post("/internal/check-trial/acme")
assert response.status_code == 200
assert response.get_json()["status"] == "already_locked"
def test_expired_trial_snapshot_error_returns_500(make_client, monkeypatch):
monkeypatch.setattr(
trial_check, "disable_users", MagicMock(side_effect=billing.SnapshotFetchError("boom"))
)
old_start = (datetime.now(timezone.utc) - timedelta(days=30)).isoformat()
client = make_client(_make_tenant(trial_start_date=old_start, trial_days=14))
response = client.post("/internal/check-trial/acme")
assert response.status_code == 500
assert "trace_id" in response.get_json()
def test_expired_trial_partial_failure_returns_502(make_client, monkeypatch):
monkeypatch.setattr(
trial_check,
"disable_users",
MagicMock(side_effect=billing.PartialFailureError("boom", succeeded=["alice"], failed=["bob"])),
)
old_start = (datetime.now(timezone.utc) - timedelta(days=30)).isoformat()
client = make_client(_make_tenant(trial_start_date=old_start, trial_days=14))
response = client.post("/internal/check-trial/acme")
assert response.status_code == 502
assert "trace_id" in response.get_json()