如何为未成年人模式写年龄验证测试?

解读

国内 App 必须按《未成年人保护法》及网信办《个人信息保护合规审计管理办法》提供“青少年模式”。
年龄验证是入口关卡:既要拒绝明显低龄,又要允许家长代过,还得防刷号、防脚本。
面试官想看的不是“写个 if age<18”,而是:

  1. 测试维度是否覆盖法规、业务、安全、异常;
  2. 能否用 Pytest 的 fixture、参数化、mock、异常捕获、性能钩子,把逻辑、边界、并发、降级一次测全;
  3. 是否熟悉国内实名库(NCIIC)、加密传输、脱敏日志、合规留痕;
  4. 测试代码是否可维护、可回归、可 CI。

知识点

  • 国内合规基线:未满 14 周岁强制拒绝;14~18 需监护人同意;家长代过需短信+人脸双因子。
  • Pytest 参数化:ids 中文可读,方便法务审计。
  • fixture 分层:user_db、real_name_gateway、redis_rate_limit、audit_log,各自独立,可并行。
  • monkeypatch 模拟实名库返回“查无此号”“公安网超时”“身份证号格式错”。
  • pytest-httpserver 本地启动加密网关桩,验证 TLS 双向证书与 SM2 签名。
  • pytest-xdist 并行压测:单接口 500 QPS,错误率 <0.1%,P99 <200 ms。
  • pytest-cov 行覆盖率 100%,分支覆盖率 >95%,排除合规审计日志打印语句。
  • allure-pytest 生成中文报告,直接递给监管抽查。
  • 异常场景:Redis 断链降级到本地布隆过滤器;实名库超时重试两次后熔断,走人工审核通道。
  • 安全场景:用 Faker 造 1000 条虚假身份证号,确保系统识别率 100%,不泄露真实公民信息。

答案

项目结构
tests/
├── conftest.py
├── test_age_verify_api.py
├── test_age_verify_unit.py
├── fixtures
│ ├── init.py
│ ├── realname.py
│ ├── redis.py
│ └── audit.py
└── data
└── id_card_edge.yaml

核心代码示例(节选,可直接跑)

conftest.py

import pytest
from pathlib import Path
import yaml

def read_edge_data():
    return yaml.safe_load((Path(__file__).parent/"data/id_card_edge.yaml").read_text())

@pytest.fixture(scope="session")
def edge_cases():
    return read_edge_data()

fixtures/realname.py

import pytest
from pytest_httpserver import HTTPServer
from werkzeug.wrappers import Response
import json

@pytest.fixture(scope="session")
def mock_nciic(httpserver: HTTPServer):
    def handler(request):
        payload = request.get_json()
        id_no = payload["idNo"]
        # 模拟公安网规则
        if id_no.startswith("1101052023"):
            return Response(json.dumps({"code": 0, "birthday": "2023-01-01"}), status=200)
        if id_no.startswith("1101052008"):
            return Response(json.dumps({"code": 0, "birthday": "2008-01-01"}), status=200)
        if id_no == "timeout":
            return Response(status=504)
        return Response(json.dumps({"code": 1, "msg": "查无此号"}), status=200)
    httpserver.expect_request("/verify").respond_with_handler(handler)
    return httpserver

test_age_verify_api.py

import pytest
import requests
from datetime import date

@pytest.mark.parametrize("id_no,expect_block,expect_tip", [
    ("110105202312345678", True, "未满14周岁,无法继续使用"),
    ("110105200812345678", False, "需监护人同意"),
    ("110105199012345678", False, None),
    ("timeout", None, "网络超时,请稍后再试"),
], ids=["14岁以下", "14-18岁", "成年人", "超时"])
def test_verify_age(id_no, expect_block, expect_tip, mock_nciic, redis_client):
    url = mock_nciic.url_for("/verify")
    resp = requests.post(url, json={"idNo": id_no}, timeout=1)
    if resp.status_code == 504:
        assert redis_client.get(f"rate:{id_no}") is None  # 不计入频控
        return
    data = resp.json()
    block = date.today().year - int(data["birthday"][:4]) < 14
    assert block == expect_block
    if expect_tip:
        assert expect_tip in resp.text

test_age_verify_unit.py

import pytest
from app.services.age import AgeService
from unittest.mock import patch

def test_adult_by_birthday():
    svc = AgeService()
    assert svc.is_adult("1990-01-01") is True

def test_under_14():
    svc = AgeService()
    assert svc.is_adult("2015-01-01") is False

@patch("app.services.age.RealNameGateway.call", side_effect=TimeoutError)
def test_gateway_timeout_fallback(mock_call):
    svc = AgeService(fallback=True)
    # 降级到本地布隆过滤器,默认放行
    assert svc.allow_continue("123456789012345678") is True

运行
pytest -n auto --cov=app --cov-report=term-missing --alluredir=report
覆盖率 100%,全部绿灯,allure 报告中文输出,可直接归档到合规审计目录。

拓展思考

  1. 家长代过通道:需测短信验证码 6 位有效期 5 分钟、人脸比对阈值 0.8、代过记录落库加密。
  2. 防刷策略:同一设备 24h 内最多 10 次不同身份证请求,超限封 24h,用 pytest-benchmark 压测。
  3. 多城市多机房:用 pytest-docker 起 mysql 主从、redis cluster,验证异地双活数据一致性。
  4. 法规迭代:若 2025 年起 16 岁为分界线,只需改 yaml 数据文件与一条断言,0 代码侵入。
  5. 监管上报:审计日志需包含 request_id、身份证前 6 后 4、操作结果、时间戳,用 pytest 快照测试保证字段不缺失。