""" tests/test_stripe_webhook.py — tests for the /webhook/stripe/ route. No call ever reaches real Stripe or a real Frappe site: stripe.Webhook. construct_event is monkeypatched per-test to simulate a valid/invalid signature, billing.disable_users/reenable_users are monkeypatched on the stripe_webhook module (the name they were imported into), and StateStore is monkeypatched to a stub class so no real SQLite file is touched — these tests exercise only the route's own tenant-lookup/dispatch/error-handling logic, which is covered separately and in depth by test_billing.py (business logic) and test_tenants.py (registry behavior). """ from unittest.mock import MagicMock import pytest import stripe import app as app_module import billing.billing as billing import billing.stripe_webhook as stripe_webhook from billing.tenants import TenantConfig, TenantRegistry class _StubStateStore: """Replaces the real StateStore so tests never touch SQLite; records the tenant_slug it was built for.""" def __init__(self, tenant_slug, db_path=None): self.tenant_slug = tenant_slug self.db_path = db_path @pytest.fixture def client(monkeypatch): monkeypatch.setattr(stripe_webhook, "StateStore", _StubStateStore) flask_app = app_module.app flask_app.config["TESTING"] = True tenant = TenantConfig( slug="acme", frappe_api_url="http://frappe.test", frappe_api_key="key", frappe_api_secret="secret", stripe_webhook_secret="whsec_acme", ) registry = TenantRegistry({"acme": tenant}) registry.frappe_client_for = MagicMock(return_value=MagicMock()) flask_app.config["TENANT_REGISTRY"] = registry with flask_app.test_client() as test_client: yield test_client def _fake_event(event_type): return {"type": event_type, "data": {"object": {"id": "in_123"}}} def test_unknown_tenant_returns_404_before_signature_is_checked(client, monkeypatch): construct_spy = MagicMock() monkeypatch.setattr(stripe.Webhook, "construct_event", construct_spy) response = client.post("/webhook/stripe/not-a-real-tenant", data=b"{}") assert response.status_code == 404 assert response.get_json()["error"] == "unknown tenant" construct_spy.assert_not_called() def test_missing_signature_returns_403(client): response = client.post("/webhook/stripe/acme", data=b"{}") assert response.status_code == 403 assert response.get_json()["error"] == "invalid signature" def test_invalid_signature_returns_403(client, monkeypatch): def raise_invalid(*args, **kwargs): raise stripe.error.SignatureVerificationError("bad signature", "sig_header") monkeypatch.setattr(stripe.Webhook, "construct_event", raise_invalid) response = client.post( "/webhook/stripe/acme", data=b"{}", headers={"Stripe-Signature": "bad"} ) assert response.status_code == 403 def test_unhandled_event_type_is_a_noop(client, monkeypatch): monkeypatch.setattr( stripe.Webhook, "construct_event", lambda *a, **k: _fake_event("customer.created") ) disable_spy = MagicMock() reenable_spy = MagicMock() monkeypatch.setattr(stripe_webhook, "disable_users", disable_spy) monkeypatch.setattr(stripe_webhook, "reenable_users", reenable_spy) response = client.post( "/webhook/stripe/acme", data=b"{}", headers={"Stripe-Signature": "valid"} ) assert response.status_code == 200 disable_spy.assert_not_called() reenable_spy.assert_not_called() def test_payment_failed_success_returns_200_and_calls_disable_users(client, monkeypatch): monkeypatch.setattr( stripe.Webhook, "construct_event", lambda *a, **k: _fake_event("invoice.payment_failed"), ) disable_spy = MagicMock(return_value={"disabled": ["alice"], "failed": []}) monkeypatch.setattr(stripe_webhook, "disable_users", disable_spy) response = client.post( "/webhook/stripe/acme", data=b"{}", headers={"Stripe-Signature": "valid"} ) assert response.status_code == 200 assert response.get_json()["status"] == "ok" 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_payment_failed_snapshot_error_returns_500(client, monkeypatch): monkeypatch.setattr( stripe.Webhook, "construct_event", lambda *a, **k: _fake_event("invoice.payment_failed"), ) monkeypatch.setattr( stripe_webhook, "disable_users", MagicMock(side_effect=billing.SnapshotFetchError("boom")), ) response = client.post( "/webhook/stripe/acme", data=b"{}", headers={"Stripe-Signature": "valid"} ) assert response.status_code == 500 assert "trace_id" in response.get_json() def test_payment_succeeded_success_returns_200_and_calls_reenable_users(client, monkeypatch): monkeypatch.setattr( stripe.Webhook, "construct_event", lambda *a, **k: _fake_event("invoice.payment_succeeded"), ) reenable_spy = MagicMock(return_value={"reenabled": ["alice"], "failed": []}) monkeypatch.setattr(stripe_webhook, "reenable_users", reenable_spy) response = client.post( "/webhook/stripe/acme", data=b"{}", headers={"Stripe-Signature": "valid"} ) assert response.status_code == 200 reenable_spy.assert_called_once() def test_payment_succeeded_partial_failure_returns_502(client, monkeypatch): monkeypatch.setattr( stripe.Webhook, "construct_event", lambda *a, **k: _fake_event("invoice.payment_succeeded"), ) monkeypatch.setattr( stripe_webhook, "reenable_users", MagicMock( side_effect=billing.PartialFailureError("boom", succeeded=["alice"], failed=["bob"]) ), ) response = client.post( "/webhook/stripe/acme", data=b"{}", headers={"Stripe-Signature": "valid"} ) assert response.status_code == 502 assert "trace_id" in response.get_json()