如何验证 NFT 元数据 URI 可访问?

解读

在国内 NFT 平台(如阿里拍卖、腾讯至信链、京东灵稀、BSN 开放联盟链)的交付流程中,链上只存 tokenID → URI 的映射,真正的图片、属性、版权信息都托管在中心化网关或 IPFS 网关。上线前必须保证:

  1. URI 拼写正确、无中文空格
  2. 返回 200 且内容类型为 application/json
  3. JSON 结构符合平台审核规范(name、description、image 字段必含,image 可访问)
  4. 国内网络能直接拉取(IPFS 需验证 4everland、NFT.Storage 网关,海外裸 IPFS 会被墙)

因此“可访问”不仅是 200 OK,还要满足合规、可解析、可渲染三层要求。面试官想考察:

  • 如何用 pytest 把“可访问”拆成可自动化、可回归的断言
  • 遇到重定向、鉴权、限流、超时、内容编码异常如何容错
  • 是否熟悉国内网关的备案、边缘加速、边缘缓存刷新机制

知识点

  1. pytest 分层设计:conftest.py 复用 session 级连接池,fixtures 提供不同链环境(主网、测试网、沙箱)
  2. requests 高级用法:timeout、retry、stream=False、allow_redirects、headers 带备案号
  3. 国内合规字段:image 字段必须 https,域名需 ICP 备案,不能出现敏感词
  4. JSON Schema 断言:jsonschema.validate,避免手写字段判断
  5. 性能与限流:pytest-xdist 并发拉取 1000 条 URI 时,需用 pytest-ratelimit 或 token bucket 限 QPS<30,防止触发网关 403
  6. 缓存刷新:阿里云 CDN、腾讯云 ECDN 刷新预热接口,测试前调用强制刷新,避免命中旧缓存
  7. 异常建模:自定义 pytest 异常 NFTUriInaccessible、NFTSchemaViolation,配合 pytest-assertion-utils 给出 diff
  8. 持续集成:GitHub Actions + 国内 Runner(华为云、阿里云)走 IPv4 单栈,避免 GitHub 裸 IP 被墙
  9. 报告:pytest-html + 企业微信机器人,失败时自动 @ 运维,附 URI、响应头、 traceroute 截图文本

答案

工程目录 nft/ ├─ tests/ │ ├─ conftest.py │ ├─ test_metadata.py │ └─ schemas/ │ └─ metadata.json ├─ requirements.txt └─ pytest.ini

conftest.py

import json
import pytest
import requests
from requests.adapters import HTTPAdapter, Retry

# 国内合规请求头
DEFAULT_HEADERS = {
    "User-Agent": "NFTMetadataBot/1.0 (ICP-备案号:京ICP备12345678号)",
    "Accept": "application/json",
}

@pytest.fixture(scope="session")
def http():
    sess = requests.Session()
    retries = Retry(total=3, backoff_factor=0.3, status_forcelist=[502, 503, 504])
    sess.mount("https://", HTTPAdapter(max_retries=retries))
    sess.headers.update(DEFAULT_HEADERS)
    yield sess
    sess.close()

@pytest.fixture(scope="session")
def schema():
    with open("tests/schemas/metadata.json") as f:
        return json.load(f)

schemas/metadata.json(平台强制规范)

{
  "type": "object",
  "properties": {
    "name": {"type": "string", "minLength": 1},
    "description": {"type": "string"},
    "image": {"type": "string", "pattern": "^https://"}
  },
  "required": ["name", "image"]
}

test_metadata.py

import jsonschema
import pytest
import requests

# 参数化 1000 条链上 URI
def id_from_token(token):
    return f"token_{token['id']}"

@pytest.mark.parametrize(
    "token",
    [{"id": i, "uri": f"https://ipfs-gateway.example.com/ipfs/QmTest/{i}"} for i in range(1000)],
    ids=id_from_token,
)
def test_metadata_uri_accessible(token, http, schema):
    uri = token["uri"]
    try:
        r = http.get(uri, timeout=10)
    except requests.exceptions.Timeout:
        pytest.fail(f"URI 超时: {uri}")

    # 1. 状态码断言
    assert r.status_code == 200, f"URI 不可访问,状态码:{r.status_code}, text: {r.text[:200]}"

    # 2. 内容类型断言
    assert "application/json" in r.headers.get("Content-Type", ""), "返回非 JSON"

    # 3. JSON 解析
    try:
        payload = r.json()
    except ValueError:
        pytest.fail("返回体不是合法 JSON")

    # 4. 字段合规
    jsonschema.validate(payload, schema)

    # 5. image 可访问
    img = payload["image"]
    img_resp = http.head(img, timeout=5)
    assert img_resp.status_code == 200, f"image 不可访问: {img}"

运行

pip install pytest pytest-xdist jsonschema requests
pytest -n 30 --dist=loadscope --html=report.html

关键断言解释

  • 超时 10 s:国内 4G/5G 弱网场景
  • head 请求验证 image:减少流量,符合 CDN 日志规范
  • jsonschema 一次性校验字段类型、必填、https 正则,避免手写 if
  • 并发 30 进程:在阿里云 8 vCPU 机器上 QPS≈300,低于网关 500 限流

拓展思考

  1. 动态链上抓取:写一个 fixture 调用区块链节点 RPC(如 BSN 开放联盟链 HTTP API),实时拿 tokenURI,而不是 hard-code 列表,保证测试即真实
  2. 签名鉴权:部分平台要求请求头带 X-Api-Key 或 JWT,可在 conftest.py 里加 autouse fixture 自动刷新 token,失败即重试
  3. 图片内容校验:除了 head 200,可下载前 8 byte 验证 magic number(如 PNG 89 50),防止 CDN 返回 200 但实为 404 HTML
  4. 灰度与回滚:把测试拆成 smoke(100 条)+ full(全量),在 GitLab CI 里用 rules:if 控制,灰度发布前只跑 smoke,全量发布后再跑 full,降低流水线时长
  5. 合规监控:将 pytest 封装成定时任务,每 30 分钟跑一次,失败自动创建飞书工单,附带 traceroute、mtr 文本,方便运维判断是运营商出口问题还是 CDN 节点问题
  6. 私有 IPFS 集群:若企业自建 IPFS,需额外验证集群 pin 状态,可在测试里调用 ipfs-cluster-ctl status CID,未 pin 立即告警,防止元数据丢失导致图片无法渲染