如何为量子任务结果写快照测试?

解读

量子任务(如 Qiskit、MindQuantum、QPanda 等框架下的线路执行)返回的结果通常包含:

  1. 概率分布 dict,如 {'00': 512, '01': 488}
  2. 带统计涨落的浮点数组,如 [0.512, 0.488]
  3. 复杂的自定义对象,如 QuantumCircuit、Result、Counts、Statevector

快照测试(snapshot testing)的核心是“先存基准,后比差异”,但量子结果天然带随机性,直接序列化会导致用例脆弱。
国内面试官想考察的是:

  • 你是否理解 pytest-snapshot 插件的底层机制
  • 能否用 fixture + 伪随机种子 + 容忍误差策略,把“不可复现”转化为“可复现”
  • 是否知道在 CI(GitHub Actions / Gitee Go / 阿里云效)里如何管理快照文件(*.snap)的版本与回滚

知识点

  1. pytest-snapshot 插件:snapshot.assert_match(data, snapshot_name) 会把 data 序列化为字符串并写入 snapshots/*.snap,第二次运行时做全文 diff
  2. 量子伪随机种子:qiskit.utils.algorithm_globals.random_seed = 42 或 numpy.random.seed(42),保证线路采样可复现
  3. 容差快照:对浮点数组使用 np.round(probs, 4) 或 pprint.pformat(sorted_counts) 后再断言,避免 1e-15 级误差
  4. 自定义序列化:为量子对象写 JSONEncoder,把 Statevector 转成列表,把 QuantumCircuit 转成 qasm 字符串,保证快照可读可 diff
  5. 快照文件治理:
    • 把 snapshots 目录提交到 Git LFS,防止仓库膨胀
    • 在 pytest.ini 里加 --snapshot-update 门禁,只有 maintainer 在 MR 里手动触发才能更新基准
  6. 并行与缓存:量子线路执行慢,用 pytest-xdist 并行时,确保每个 worker 使用独立种子(seed = worker_id + 42),避免快照冲突

答案

下面给出可直接落地的工程级示例,覆盖“单测-快照-CI”全链路,符合国内代码审查习惯。

项目结构 quantum_proj/ ├── quantum_app/ │ └── circuit_runner.py ├── tests/ │ ├── init.py │ ├── conftest.py │ └── test_circuit_runner.py ├── snapshots/ │ └── test_circuit_runner/ │ └── test_bell_counts.snap └── pytest.ini

  1. 业务代码 circuit_runner.py
from qiskit import QuantumCircuit, execute, Aer
import numpy as np

def run_bell_shots(seed: int = 42):
    """返回 {'00': xxx, '11': yyy},已固定种子"""
    from qiskit.utils import algorithm_globals
    algorithm_globals.random_seed = seed
    qc = QuantumCircuit(2)
    qc.h(0)
    qc.cx(0, 1)
    qc.measure_all()
    backend = Aer.get_backend('qasm_simulator')
    job = execute(qc, backend, shots=1024)
    counts = job.result().get_counts()
    # 排序保证序列化一致性
    return dict(sorted(counts.items()))
  1. conftest.py:注册快照路径与更新策略
import pytest
from pathlib import Path

@pytest.fixture(scope='session')
def snapshot_dir():
    return Path(__file__).parent / '__snapshots__'
  1. 测试用例 test_circuit_runner.py
import json
from quantum_app.circuit_runner import run_bell_shots

def test_bell_counts(snapshot):
    counts = run_bell_shots(seed=42)
    # 把 dict 转成漂亮字符串,避免顺序差异
    snapshot_text = json.dumps(counts, indent=2, ensure_ascii=False)
    snapshot.assert_match(snapshot_text, 'test_bell_counts.snap')
  1. 首次生成快照
$ pytest tests/test_circuit_runner.py::test_bell_counts --snapshot-update
# 生成 __snapshots__/test_circuit_runner/test_bell_counts.snap
  1. 后续回归
$ pytest
# 若量子库升级导致统计偏差超过阈值(如 1%),用例会失败
# 确认是预期变更后,再跑一次 --snapshot-update 并提交 MR
  1. CI 模板(.github/workflows/quantum.yml)
name: Quantum Snapshot CI
on: [push, pull_request]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v4
        with:
          python-version: "3.11"
      - run: pip install -r requirements.txt
      - run: pytest --cov=quantum_app
      - name: Upload snapshot diff
        if: failure()
        uses: actions/upload-artifact@v3
        with:
          name: snapshot-diff
          path: __snapshots__/
  1. 浮点容忍度增强(可选) 若返回的是概率数组,可写自定义 matcher:
def test_bell_probs(snapshot):
    probs = np.array([0.512, 0.488])
    snapshot.assert_match(np.round(probs, 3).tolist(), 'test_bell_probs.snap')

至此,量子任务快照测试即可在本地与云效流水线中稳定运行,满足国内企业对“可回滚、可审查、可并行”的质量门禁要求。

拓展思考

  1. 真机噪声快照:真机执行结果不可复现,可把快照改成“分布形状”检验,用 χ² 或 KL 散度做假设检验,而非全文 diff
  2. 多版本快照:量子芯片校准参数每周更新,可在快照文件名里加入 chip_id+calibration_date,实现“一芯一基准”
  3. 混合测试:把快照测试与属性测试(hypothesis)结合,自动生成随机线路,验证“所有双比特门 Bell 态概率分布快照”都在容忍区间
  4. 合规与出口管制:国内量子云服务平台(如百度量易、华为 HiQ)对线路日志有审计要求,快照文件可能含敏感参数,需在 CI 中加密存储并设置 90 天自动清理
  5. 性能优化:量子线路执行耗时,快照测试应放在“慢速”标记(pytest.mark.slow),在 MR 阶段只跑冒烟用例,夜间定时全量回归