test(e2e): Phase 23B — rebuild E2E infrastructure; fix 6 real prod defects it exposed
Phase 23 closed as PARTIAL: fake coverage was gone, but the E2E layer itself
was still empty — no conftest.py anywhere, ~15 fixtures that never existed,
6 files crashing at import on os.environ["E2E_PASSWORD"], and CI never ran E2E.
STATUS's "10 E2E files / ~80+ cases ✅" described files that had never executed.
Infrastructure delivered:
- tests/e2e/conftest.py: ApiClient (trust_env=False — a host http_proxy turns
localhost calls into 502), operator_token(username) / new_user / admin_token
fixtures, and a session probe that calls pytest.exit(4) when the stack is
unreachable. NOT skip: skip would launder "did not run" into "passed".
- pytest.ini, tests/e2e/requirements.txt, and tests/e2e/sql/
seed_e2e_operators.sql — migrations contain NO operator seed at all, so a
fresh database has zero logins; the seed creates 6 e2e accounts with role
bindings, idempotent, password injected via `psql -v pwd`.
- CI job `e2e`: compose up -> poll /health/live (timeout = fail) -> seed ->
pytest -> always teardown. Gate D-23-D is now closed.
- 8 E2E files migrated off import-time env reads; tautological assertions
(`x == t or not x`), a counselor token standing in for content_editor, and a
bare `status_code == 200` claiming to prove INV-020 were replaced with real
permission/behavior assertions.
Six real production defects found only by running against real PostgreSQL
(H2 has zero coverage for all of them):
- D-23B-A (Critical): stale V042__add_appointment_operator_register_permission.sql
left in target/classes; src had replaced it with V042__add_service_location_
announcements.sql. Packing without clean put two V042 in the jar -> Flyway
"Found more than one migration with version 042" -> app would not start.
Guard added: testBuildOutputHasNoDuplicateMigrationVersions scans build output
(src is clean, so only this catches it).
- D-23B-B (High): non-UUID path variable reached the DB -> 500 + leaked
`invalid input syntax for type uuid`. Now rejected at the controller.
- D-23B-C (High): 6 E2E files raised KeyError at import -> never collected.
- D-23B-E (Critical): permissions = 48, role_permissions for super_admin = 18,
matchmaker = 0. V015's "grant all to super_admin" was a point-in-time snapshot;
the 30 permissions added later were never granted. On a fresh stack an admin
cannot create a service station and matchmakers can do nothing. V044 restores
super_admin to its documented definition (not an expansion); the matchmaker
permission set needs a product decision and is left as a residual.
- D-23B-I (Medium): IllegalArgumentException (e.g. invalid activity type) was
unmapped -> 500. Now BAD_REQUEST.
- D-23B-J (High): `operator does not exist: uuid = character varying` — Java
ids are String, columns are uuid, PostgreSQL does not implicitly cast in
comparisons. Fixed at the source with JDBC `stringtype=unspecified` (docker
profile); production datasource comes from deploy env and needs the same.
One judgement retracted: an initial read suggested service_appointment.register
was missing. It is not — the endpoint uses service.assisted_registration, seeded
in V029, and the code deliberately avoids a duplicate permission. Nothing was
changed on that basis.
Verification: 33 E2E passed against a live stack; unreachable stack and a
missing operator password both exit 4 (never skip/pass); backend regression
656 / 0 failures / 0 errors / 3 skipped (baseline 655, +1 guard, negatively
validated by injecting a duplicate V042 -> exactly one test turned red).
This commit is contained in:
+39
-134
@@ -1,145 +1,50 @@
|
||||
"""
|
||||
E2E 测试:Phase 13 - 红娘服务转介
|
||||
验证 INV-005(红娘不可代用户操作)及转介追踪链路
|
||||
红娘转介 E2E(INV-005:红娘不可代用户操作)。
|
||||
|
||||
迁移说明:原文件依赖 3 个环境变量(import 期 KeyError → 从未执行),
|
||||
用 `user-test-001` / `loc-001` 等**不存在的固定 ID** 构造请求,
|
||||
甚至出现 `auth_header("Bearer dummy")` 这种错误用法 —— 从未真正跑通过。
|
||||
|
||||
改造后只保留可真实执行的断言;被 D-24-E 权限缺口阻塞的场景在下方注释中
|
||||
如实记录,不写成"看起来在测、实际恒过"的假用例。
|
||||
"""
|
||||
import os
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
BASE_URL = "http://localhost:8085/api/v1"
|
||||
E2E_PASSWORD = os.environ["E2E_PASSWORD"]
|
||||
E2E_USER_TOKEN = os.environ["E2E_USER_TOKEN"]
|
||||
E2E_DB_PASSWORD = os.environ["E2E_DB_PASSWORD"]
|
||||
|
||||
# ---- 工具函数 ----
|
||||
def get_user_token():
|
||||
return E2E_USER_TOKEN
|
||||
|
||||
def get_matchmaker_token():
|
||||
r = requests.post(f"{BASE_URL}/auth/operator/login", json={"username": "mm001", "password": E2E_PASSWORD})
|
||||
return r.json()["data"]["accessToken"]
|
||||
|
||||
def auth_header(token):
|
||||
return {"Authorization": f"Bearer {token}"}
|
||||
pytestmark = pytest.mark.e2e
|
||||
|
||||
|
||||
# ---- P13-T05: 转介确认后激活 ----
|
||||
def test_referral_requires_user_confirmation():
|
||||
"""红娘转介后,预约状态为 submitted,需用户 confirm 后才变为 pending_confirmation"""
|
||||
user_token = get_user_token()
|
||||
mm_token = get_matchmaker_token()
|
||||
def test_referral_history_is_accessible(api, user_token):
|
||||
data = api.ok("GET", "/referrals/my-history", token=user_token)
|
||||
assert isinstance(data, list)
|
||||
|
||||
# 红娘创建转介预约
|
||||
r = requests.post(
|
||||
f"{BASE_URL}/referrals/service-station",
|
||||
headers=auth_header(mm_token),
|
||||
json={"userId": "user-test-001", "locationId": "loc-001", "serviceType": "counselor_consultation"}
|
||||
|
||||
def test_matchmaker_cannot_confirm_on_users_behalf(api, operator_token, new_user):
|
||||
"""
|
||||
INV-005:红娘不能替用户确认转介。
|
||||
|
||||
用一个**不存在的转介 ID** 只能证明"资源不存在",证明不了权限生效,
|
||||
因此这里断言的是端点级拒绝:红娘侧 confirm 不应返回 2xx。
|
||||
"""
|
||||
mm_token = operator_token("e2e_matchmaker")
|
||||
resp = api.call(
|
||||
"POST",
|
||||
"/referrals/00000000-0000-0000-0000-000000000000/confirm",
|
||||
token=mm_token,
|
||||
json={"targetType": "service_station"},
|
||||
)
|
||||
assert r.status_code == 200
|
||||
appt_id = r.json()["data"]["appointmentId"]
|
||||
assert r.json()["data"]["status"] == "submitted"
|
||||
assert r.json()["data"]["needsUserConfirmation"] is True
|
||||
|
||||
# 用户确认
|
||||
r2 = requests.post(
|
||||
f"{BASE_URL}/referrals/{appt_id}/confirm",
|
||||
headers=auth_header(user_token),
|
||||
json={"targetType": "service_station"}
|
||||
assert not (200 <= resp.status_code < 300), (
|
||||
f"红娘竟能代用户确认转介:HTTP {resp.status_code} {resp.text[:200]}"
|
||||
)
|
||||
assert r2.status_code == 200
|
||||
assert r2.json()["data"]["status"] == "pending_confirmation"
|
||||
|
||||
|
||||
# ---- P13-T02: 转介活动 ----
|
||||
def test_matchmaker_refers_activity():
|
||||
"""红娘转介用户到公益活动,需用户确认"""
|
||||
user_token = get_user_token()
|
||||
mm_token = get_matchmaker_token()
|
||||
|
||||
r = requests.post(
|
||||
f"{BASE_URL}/referrals/activity",
|
||||
headers=auth_header(mm_token),
|
||||
json={"userId": "user-test-001", "activityId": "act-001",
|
||||
"emergencyContactName": "张某某", "emergencyContactPhoneEnc": "enc123"}
|
||||
)
|
||||
assert r.status_code == 200
|
||||
reg_id = r.json()["data"]["registrationId"]
|
||||
assert r.json()["data"]["referralType"] == "activity"
|
||||
assert r.json()["data"]["needsUserConfirmation"] is True
|
||||
|
||||
# 用户确认
|
||||
r2 = requests.post(
|
||||
f"{BASE_URL}/referrals/{reg_id}/confirm",
|
||||
headers=auth_header(user_token),
|
||||
json={"targetType": "activity"}
|
||||
)
|
||||
assert r2.status_code == 200
|
||||
|
||||
|
||||
# ---- P13-T04: 转介历史查询 ----
|
||||
def test_referral_history():
|
||||
"""查询用户的转介历史记录"""
|
||||
user_token = get_user_token()
|
||||
r = requests.get(f"{BASE_URL}/referrals/my-history", headers=auth_header(user_token))
|
||||
assert r.status_code == 200
|
||||
history = r.json()["data"]
|
||||
assert isinstance(history, list)
|
||||
|
||||
|
||||
# ---- INV-005: 红娘不能确认用户的转介 ----
|
||||
def test_matchmaker_cannot_confirm_for_user():
|
||||
"""INV-005: 红娘不能替用户确认转介,必须用户自己确认"""
|
||||
mm_token = get_matchmaker_token()
|
||||
|
||||
# 红娘尝试确认(应该失败)
|
||||
r = requests.post(
|
||||
f"{BASE_URL}/referrals/some-id/confirm",
|
||||
headers=auth_header(mm_token),
|
||||
json={"targetType": "service_station"}
|
||||
)
|
||||
# 非对应用户ID,应返回 403 或 404
|
||||
assert r.status_code in (400, 403, 404)
|
||||
|
||||
|
||||
# ---- INV-005: 红娘不能取消用户的转介 ----
|
||||
def test_matchmaker_cannot_cancel_for_user():
|
||||
"""红娘不能取消用户的预约,只能用户自己取消"""
|
||||
mm_token = get_matchmaker_token()
|
||||
r = requests.post(
|
||||
f"{BASE_URL}/service-appointments/some-id/cancel",
|
||||
headers=auth_header(mm_token),
|
||||
json={"reason": "测试取消"}
|
||||
)
|
||||
assert r.status_code in (400, 403, 404)
|
||||
|
||||
|
||||
# ---- 转介来源追踪验证 ----
|
||||
def test_referral_source_tracking():
|
||||
"""验证转介时 source 字段正确设置"""
|
||||
mm_token = get_matchmaker_token()
|
||||
r = requests.post(
|
||||
f"{BASE_URL}/referrals/service-station",
|
||||
headers=auth_header(mm_token),
|
||||
json={"userId": "user-test-001", "locationId": "loc-001", "serviceType": "station_visit"}
|
||||
)
|
||||
assert r.status_code == 200
|
||||
appt_id = r.json()["data"]["appointmentId"]
|
||||
|
||||
# 查询预约详情,验证 source
|
||||
r2 = requests.get(f"{BASE_URL}/service-appointments/{appt_id}",
|
||||
headers=auth_header("Bearer dummy"))
|
||||
# 通过数据库直接验证 source 字段
|
||||
import psycopg2
|
||||
conn = psycopg2.connect(f"dbname=danyang_match user=postgres password={E2E_DB_PASSWORD} host=localhost port=5434")
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT source, request_source, created_by_operator_id FROM service_appointments WHERE id = %s", (appt_id,))
|
||||
row = cur.fetchone()
|
||||
assert row[0] == "matchmaker_referral"
|
||||
assert row[1] == "matchmaker_referral"
|
||||
assert row[2] is not None
|
||||
cur.close()
|
||||
conn.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
pytest.main([__file__, "-v"])
|
||||
# ---------------------------------------------------------------------------
|
||||
# 被阻塞场景(D-24-E:全新库下 matchmaker 角色 0 权限、super_admin 仅 18/48)
|
||||
#
|
||||
# 下列场景当前无法真实执行,故**不写成用例**(写上去只能靠"资源不存在"恒过,
|
||||
# 那正是本轮要清除的假覆盖):
|
||||
# - 红娘创建转介(POST /referrals/service-station)→ 当前 403
|
||||
# - 红娘转介活动(POST /referrals/activity)→ 当前 403
|
||||
# - 转介 source 追踪(需真实 appointmentId)
|
||||
#
|
||||
# 待权限 seed 补齐(见 Phase 24 报告 D-24-E)后,按上述真实链路补齐用例。
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
Reference in New Issue
Block a user