如何为 GDPR 数据删除写端到端测试?
解读
面试官问“端到端”而非单元测试,重点在验证“用户触发删除 → 系统级联清理 → 外部同步 → 无法恢复”这一完整链路在中国落地时的合规性与技术正确性。需体现:
- 真实环境:用 pytest 驱动完整服务(含数据库、缓存、对象存储、消息队列、搜索引擎、备份、第三方 SaaS)。
- 合规证据:日志、备份清理、异步任务完成、下游系统同步成功。
- 不可恢复:二次查询、冷备份、只读副本均返回 404 或空。
- 性能与并发:批量删除不击穿限流,事务不残留。
- 中国特色:数据跨境同步、本地化备份、等级保护 2.0 留存期、政企客户审批流。
知识点
- pytest 端到端三层 fixture:env(docker-compose / k8s)、data(最小匿名数据集)、client(真实域名 + 合法 JWT)。
- 依赖注入:用 fixture 工厂返回“已登录 EU 用户”与“内部运营角色”两种身份,验证 403/202 场景。
- 参数化与标记:@pytest.mark.gdpr、@pytest.mark.e2e、@pytest.mark.delete_cascade,支持
pytest -m gdpr -n auto并行。 - 异步断言:pytest-asyncio + tenacity 轮询异步任务,直到“删除完成”事件落库。
- 数据不可达断言:对 MySQL、Redis、ES、OSS、Hive 分别 SELECT/GET/Search,期望空结果集;用 pytest-raises 验证二次删除返回 410 Gone。
- 备份清理:调用真实备份系统 API,断言“备份链中该 user_id 快照被物理擦除”返回 200。
- 日志审计:通过 pytest 的 caplog + 自定义 hook,在 teardown 阶段解析 JSON 日志,必须出现 GDPR_DELETE 审计 ID 与操作员邮箱。
- 性能:pytest-benchmark 统计单条与 1k 条批量删除 P99 延迟;同时用 pytest-xdist 并发 50 线程,验证限流 429 触发。
- 数据跨境:fixture 里切换“境内/境外”路由,断言删除请求只落在境内可用区,无出境流量。
- 合规留存:用 freezegun 将时间拨到 15 天后,再次断言“匿名化留存表”自动截断,数据行数为 0。
- 失败回滚:在 PostgreSQL 端触发异常,断言事务回滚后用户数据依旧可查询,确保“删除可重入”。
- 报告:pytest-html + pytest-json-report 双输出,供法务上传内控系统。
答案
# conftest.py
import pytest, uuid, asyncio, tenacity
from datetime import datetime, timedelta
from httpx import AsyncClient
from sqlalchemy import text
from testcontainers.compose import DockerCompose
@pytest.fixture(scope="session")
def compose():
with DockerCompose(".", compose_file_name="docker-compose-e2e.yml") as c:
c.wait_for("http://localhost:8000/health")
yield c
@pytest.fixture
async def async_client(compose):
async with AsyncClient(base_url="http://localhost:8000") as ac:
yield ac
@pytest.fixture
def eu_user(async_client):
uid = str(uuid.uuid4())
r = async_client.post("/register/eu", json={"email": f"{uid}@test.com"})
assert r.status_code == 201
yield r.json() # 含 user_id & jwt
@pytest.fixture
def operator_client(async_client):
r = async_client.post("/auth/operator", json={"key": "OP_KEY"})
assert r.status_code == 200
token = r.json()["token"]
async_client.headers.update({"Authorization": f"Bearer {token}"})
return async_client
# test_gdpr_delete.py
import pytest, asyncio, tenacity, uuid
from sqlalchemy import text
@pytest.mark.gdpr
@pytest.mark.e2e
class TestGDPRDelete:
@tenacity.retry(stop=tenacity.stop_after_delay(30), wait=tenacity.wait_fixed(1))
async def wait_job_done(self, async_client, job_id):
r = await async_client.get(f"/gdpr/job/{job_id}")
assert r.status_code == 200
assert r.json()["status"] == "completed"
async def test_single_user_cascade_delete(self, async_client, eu_user, db_engine, redis, es, oss_bucket):
user_id = eu_user["user_id"]
# 1. 触发删除
r = await async_client.delete(f"/gdpr/user/{user_id}", headers={"Authorization": f"Bearer {eu_user['jwt']}"})
assert r.status_code == 202
job_id = r.json()["job_id"]
# 2. 等待异步任务完成
await self.wait_job_done(async_client, job_id)
# 3. 主库不可查
async with db_engine.begin() as conn:
row = await conn.execute(text("SELECT 1 FROM users WHERE id=:uid"), {"uid": user_id})
assert row.first() is None
# 4. 缓存不可达
assert await redis.get(f"user:{user_id}") is None
# 5. 搜索索引无残留
resp = await es.search(index="users", body={"query": {"term": {"_id": user_id}}})
assert resp["hits"]["total"]["value"] == 0
# 6. 对象存储头像删除
assert not await oss_bucket.object_exists(f"avatar/{user_id}.jpg")
# 7. 二次删除返回 410
r = await async_client.delete(f"/gdpr/user/{user_id}", headers={"Authorization": f"Bearer {eu_user['jwt']}"})
assert r.status_code == 410
@pytest.mark.parametrize("batch_size", [10, 100, 500])
async def test_batch_delete_performance(self, async_client, operator_client, batch_size, benchmark):
user_ids = [str(uuid.uuid4()) for _ in range(batch_size)]
# 预插入数据
await async_client.post("/gdpr/batch_insert", json={"ids": user_ids})
def run():
return asyncio.run(operator_client.delete("/gdpr/batch", json={"user_ids": user_ids}))
r = benchmark(run)
assert r.status_code == 202
# 等待全部完成
await self.wait_job_done(async_client, r.json()["job_id"])
async def test_backup_snapshots_scrubbed(self, async_client, eu_user, backup_api):
user_id = eu_user["user_id"]
# 先触发删除
r = await async_client.delete(f"/gdpr/user/{user_id}", headers={"Authorization": f"Bearer {eu_user['jwt']}"})
job_id = r.json()["job_id"]
await self.wait_job_done(async_client, job_id)
# 调用备份系统,断言该 user 快照被擦除
snaps = await backup_api.list_snapshots(user_id=user_id)
assert snaps == []
def test_audit_log_present(self, eu_user, caplog):
# 确保日志里有 GDPR 审计字段
assert any("GDPR_DELETE" in rec.message and eu_user["user_id"] in rec.message for rec in caplog.records)
运行命令:
pytest -m gdpr --tb=short -n 4 --html=report.html --json-report
通过 4 进程并行,报告自动上传至内控平台,满足国内上市科技公司审计要求。
拓展思考
- 数据匿名化与删除的边界:国内《个人信息保护法》第 47 条允许“匿名化”后留存,需在测试里用差分隐私指标验证“不可识别”。
- 跨境同步延迟:若下游 SaaS 在欧盟,需测试“删除指令重试 + 幂等令牌”,并在 pytest 侧 mock 网络分区。
- 只读库延迟:MySQL 延迟复制 24h,测试用 freezegun 加速时间,验证 24h 后快照也被清理。
- 灰度删除:用 pytest 的 marker 区分“灰度/全量”,在 CI 阶段只跑灰度,生产全量。
- 法务审批流:在 fixture 里调用内部审批 API,拿到电子签章后再真正触发删除,确保“双人复核”合规。
- 性能退化:定期在 nightly CI 跑历史版本对比,用 pytest-benchmark 的
--compare功能,防止代码劣化导致删除超时。