Files
member-portal/tests/test_resolve_payer.py
T
inference-admin 9c10e627fc
ci/woodpecker/push/woodpecker Pipeline was canceled
resolve payer: read the response's JSON (the stub hid this)
_oc_graphql_post returns the RESPONSE — it is a retrying wrapper around
client.post — so fetch_account_by_slug has to call .json() on it. My unit test
stubbed it as a dict, so the test passed and the first live call in the container
died with "Response object has no attribute get".

The test now stubs the real shape (a response wrapper with .json()). Folding it
in here rather than hiding it: a stub that does not match the real return shape
certifies nothing.
2026-11-13 22:13:22 +00:00

123 lines
5.2 KiB
Python

#!/usr/bin/env python3
"""Regression test: a first-time contributor's order must not be dropped in silence.
WHY THIS EXISTS
On 2026-11-13 21:59:43 OC delivered `order.processed` for a live $5/month
membership (Conor W, conor.canaday@gmail.com, order or_eU8gRkrPCvFsaYHrgiCfz).
The portal answered 200 and did nothing: the membership branch resolves the
payer with
members = await fetch_members()
member = next((m for m in members if m["slug"] == slug), None)
and for a FIRST-TIME contributor the payer's OC account is not in the
collective's members list yet — OC reports them as guest-…/incognito-…. So
`member` was None, the whole branch fell through, and because the payload had
arrived successfully there was no error to record either. No account, no
welcome email, no credit, no log line. The sweep's unmapped-backers check
found it hours later, which is the wrong place to find it.
The fix resolves the payer from the order's account slug (`Individual.email`,
which OC exposes for an ordinary guest checkout), and when even that yields no
email it says so at ERROR level. A payment we cannot attribute is news, never
a shrug.
The "silent no-op" shape is the actual defect here: an `if` with no `else` on a
money path, where the absence of an action leaves no trace.
"""
import asyncio
import os
import pathlib
import sys
import tempfile
ROOT = pathlib.Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
os.environ["DB_PATH"] = os.path.join(tempfile.mkdtemp(), "payer-fixture.db")
import app.main as m # noqa: E402
m.DB_PATH = os.environ["DB_PATH"]
m.OC_PERSONAL_TOKEN = "test-token"
FAILS = []
def check(cond, msg):
print((" ok " if cond else " FAIL ") + msg)
if not cond:
FAILS.append(msg)
REAL_POST = m._oc_graphql_post
class FakeResponse:
"""Mirror httpx.Response: the REAL _oc_graphql_post returns a response, not
parsed JSON. An earlier stub returned a dict, the test passed, and the first
live call died with 'Response object has no attribute get' — a stub that does
not match the real return shape certifies nothing."""
def __init__(self, payload):
self._payload = payload
def json(self):
return self._payload
def fake_post(payload):
"""Stand in for OC's GraphQL endpoint (the response wrapper, not the JSON)."""
async def _post(client, json_body, headers=None, attempts=2):
return FakeResponse(payload)
return _post
print("1. an ordinary guest checkout resolves to the payer's email")
m._oc_graphql_post = fake_post({"data": {"account": {
"__typename": "Individual", "id": "acc_x", "name": "Conor W",
"slug": "guest-71e9d110", "email": "Conor.Canaday@Gmail.com", "isIncognito": False}}})
acct = asyncio.run(m.fetch_account_by_slug("guest-71e9d110"))
check(acct and acct["email"] == "conor.canaday@gmail.com",
f"the email is returned and normalised (got {acct and acct.get('email')!r})")
check(acct and acct["name"] == "Conor W", "the name comes back too, for the welcome email")
print("2. an incognito profile yields NO email — and says so rather than guessing")
m._oc_graphql_post = fake_post({"data": {"account": {
"__typename": "Individual", "id": "acc_y", "name": "Incognito",
"slug": "incognito-5ad60182", "email": None, "isIncognito": True}}})
acct = asyncio.run(m.fetch_account_by_slug("incognito-5ad60182"))
check(acct is not None and acct.get("email") is None,
"incognito: the account is returned, the email is None (a slug is not an address)")
print("3. failures and edge cases never raise — the caller must be able to report")
m._oc_graphql_post = fake_post({"data": {"account": None}})
check(asyncio.run(m.fetch_account_by_slug("guest-nope")) is None,
"an account OC does not know returns None")
m._oc_graphql_post = fake_post({})
check(asyncio.run(m.fetch_account_by_slug("guest-nope")) is None,
"an empty payload returns None")
def boom(client, json_body, headers=None, attempts=2):
raise RuntimeError("OC read timed out")
m._oc_graphql_post = boom
check(asyncio.run(m.fetch_account_by_slug("guest-x")) is None,
"a failing lookup returns None instead of dying mid-webhook")
check(asyncio.run(m.fetch_account_by_slug("")) is None, "an empty slug is not looked up")
m.OC_PERSONAL_TOKEN = ""
check(asyncio.run(m.fetch_account_by_slug("guest-x")) is None,
"with no OC token configured there is no lookup to make")
m.OC_PERSONAL_TOKEN = "test-token"
print("4. the webhook branch: the fix is present, and its silent-fallthrough shape is gone")
src = (ROOT / "app" / "main.py").read_text()
branch = src[src.index('if slug and "membership" in tier_name.lower()'):]
branch = branch[:branch.index("elif slug and first_payment")]
check("fetch_account_by_slug(slug)" in branch,
"the branch resolves an unknown payer by account email")
check("logger.error(" in branch and "NOBODY was provisioned or credited" in branch,
"an unresolvable payer is logged at ERROR — not swallowed")
check(branch.count("if member:") == 1 and "logger.warning(" in branch,
"a resolved-by-email payer is announced in the log")
m._oc_graphql_post = REAL_POST
print()
if FAILS:
print(f"resolve payer: {len(FAILS)} FAILURE(S)")
sys.exit(1)
print("resolve payer: OK — first-time payers resolve, unresolvable ones are loud")