Quantum Software Testing in CI: Build Regression Suites for Circuits, Simulators, and Hardware
quantum software testingquantum circuit unit testingCI/CDregression testingQiskitCirqPennyLanepytest

Quantum Software Testing in CI: Build Regression Suites for Circuits, Simulators, and Hardware

SSharp Qbit Lab
2026-11-21
8 min read

Build reliable quantum CI with layered circuit tests, statistical assertions, seeded runs, simulator checks, and scheduled hardware validation.

Quantum circuits need more than a single successful simulator run. A reliable regression suite checks deterministic structure, mathematical invariants, probabilistic measurement results, transpilation effects, and the gap between simulation and real hardware. This guide presents a practical CI workflow for Qiskit, Cirq, and PennyLane projects, including pytest organization, seeded experiments, statistical tolerances, and a recurring review process for SDK and backend changes.

Overview

Quantum software testing is difficult for a reason that is easy to overlook: many circuits are probabilistic by design. A test that expects one exact bitstring may fail even when the circuit is correct, while a test that accepts any result may pass after a serious regression. The answer is to match each assertion to the property being tested.

Start by separating your test suite into four layers:

  • Structural tests verify qubit counts, gate placement, parameter binding, measurement mapping, and circuit depth.
  • Deterministic unit tests check small circuits whose ideal output is known, such as basis-state preparation, inverse operations, and simple arithmetic.
  • Statistical tests compare sampled distributions, expectation values, or probabilities using tolerances appropriate to the number of shots.
  • Integration tests verify transpilation, noise models, provider adapters, serialization, and execution on selected simulator or hardware targets.

This layered approach keeps pull-request feedback fast without treating hardware output as if it were a deterministic local function. It also makes failures easier to diagnose: a structural failure points toward circuit construction, whereas a distribution failure may involve shot noise, a changed noise model, or backend calibration.

Pin the Python and SDK versions used by CI, record the simulator configuration, and preserve the circuit or intermediate representation that produced a failure. Framework APIs and backend behavior change over time, so a reproducible test must capture more than the final assertion.

What to track

1. Circuit identity and structure

Give important circuits a stable identity and test their basic shape. Useful fields include logical qubit count, classical bit count, parameter count, gate histogram, depth before and after transpilation, and measurement layout. These checks catch accidental changes such as an extra reset, a missing measurement, or a transpiler pass that produces an unexpectedly deep circuit.

Do not make every structural value immutable. Some optimization passes are expected to change gate counts. Instead, define explicit contracts: for example, a circuit may require no more than a specified depth budget, or it may need to preserve a symmetry and measurement register mapping.

2. Mathematical invariants

Invariants are often stronger than expected-output tests. Depending on the algorithm, test properties such as probability normalization, conservation of parity, Hermitian expectation-value bounds, reversibility, or agreement between a circuit and its inverse. For a statevector simulator, probabilities should sum approximately to one. For a sampled experiment, the counts should sum to the requested shot count.

For variational circuits, test parameter binding separately from optimization. A useful unit test binds a known parameter vector and checks an expectation value or symmetry. It should not depend on a training loop converging, because optimizer behavior is a separate concern. See the parameterized quantum circuit guide for related result-management practices.

3. Statistical measurement behavior

Shot-based tests need acceptance bands. If an ideal circuit produces a target probability p and uses N independent shots, the approximate standard deviation of the measured proportion is sqrt(p(1-p)/N). This is a planning aid, not a universal pass rule: hardware noise, readout error, correlation, and repeated experiments can widen the observed variation.

For a simple proportion, use an absolute tolerance that reflects both sampling uncertainty and known experiment noise. For distributions, compare total variation distance, selected probabilities, or an application-specific metric rather than requiring every low-probability outcome to match exactly. Always report the observed counts, shots, seed, backend, and tolerance when a test fails.

4. Seeds and reproducibility

Seed every component that supports deterministic seeding: circuit sampling, simulator randomness, parameter initialization, data shuffling, and classical optimization. A seed does not make hardware deterministic, and it may not control every provider or parallel execution path. Treat it as a reproducibility aid, not a guarantee.

Use at least two modes where practical: a fixed-seed diagnostic run for debugging and an unseeded or multi-seed run for robustness. If a test passes only for one seed, the test may be exposing an unstable algorithm rather than a stable implementation.

5. Simulator and hardware metadata

Record the execution target, SDK version, Python version, transpilation options, shot count, noise model, mitigation settings, and timestamp. Hardware tests should also retain the backend name and any available calibration context. This information turns an unexplained failure into an experiment that can be reproduced or compared later.

For a broader reporting checklist, use the quantum experiment reporting template. Backend choice and calibration data should be reviewed separately from circuit correctness; the backend selection workflow provides that context.

Testing strategy comparison

StrategyBest useTypical speedMain risk
Structural assertionDetect accidental circuit or transpilation changesVery fastCan miss semantic errors
Exact small-circuit testValidate gates, measurements, and known statesFastDoes not represent larger workloads
Distribution testValidate sampled probabilities or countsFast to moderateFalse failures from tight tolerances
Noisy simulator testExercise noise-aware logic and mitigationModerateNoise model may not represent hardware
Hardware smoke testCheck provider integration and execution assumptionsSlow or variableQueue, calibration, and policy changes

A reusable pytest project template

A small project can separate circuit definitions, adapters, fixtures, and test classes:

quantum-project/
  src/
    circuits.py
    backends.py
  tests/
    test_structure.py
    test_ideal_behavior.py
    test_statistics.py
    test_integration.py
  conftest.py
  pyproject.toml
  .github/workflows/ci.yml

The exact import and execution calls differ between SDK releases, so keep framework-specific code behind a narrow adapter. The tests should consume a common result shape such as counts, probabilities, expectation values, and metadata.

import math
import pytest

@pytest.mark.parametrize('builder', [build_bell_circuit])
def test_circuit_structure(builder):
    circuit = builder()
    assert logical_qubit_count(circuit) == 2
    assert has_measurements(circuit)


def test_probability_normalization():
    result = run_ideal_simulator(build_bell_circuit(), shots=None)
    assert math.isclose(sum(result.probabilities.values()), 1.0, abs_tol=1e-9)


def test_bell_distribution():
    result = run_sampler(build_bell_circuit(), shots=4000, seed=1234)
    observed = result.probability('00') + result.probability('11')
    assert observed >= 0.97
    assert result.probability('01') <= 0.03
    assert result.probability('10') <= 0.03

In a production repository, replace the illustrative adapter names with wrappers for the selected Qiskit, Cirq, or PennyLane execution path. Avoid scattering SDK-specific result parsing through every test. That design makes a framework upgrade a contained adapter change and lets the same acceptance logic run against multiple execution methods.

Cadence and checkpoints

Run the fastest tests on every pull request. This usually includes structural assertions, small exact circuits, parameter-binding checks, and a limited number of seeded statistical tests. Keep these tests independent of credentials, queues, and external services.

Run noisy-simulator and transpilation tests on pull requests when their runtime is predictable. Otherwise, run them on a scheduled workflow and whenever circuit construction, compiler settings, noise models, or SDK dependencies change.

Reserve real-hardware validation for scheduled jobs, release candidates, and changes that affect provider integration or hardware assumptions. A practical cadence is monthly or quarterly, depending on execution access and project risk. The job should use a small smoke-test circuit, a documented shot budget, and broad but meaningful acceptance criteria. Do not block every code change on an external queue unless the project genuinely requires that guarantee.

At each checkpoint, review:

  1. Python and SDK version pins and lockfiles.
  2. Deprecated or changed execution and result APIs.
  3. Transpiler output, depth, and measurement mapping.
  4. Simulator seeds, noise-model definitions, and tolerance calculations.
  5. Hardware target availability, credentials, queue behavior, and execution cost.
  6. Whether stored golden results still describe the intended algorithm.

Keep a small baseline record rather than a giant snapshot. Store representative circuits, expected invariants, distribution summaries, and resource measures such as qubits, depth, and shots. The resource estimation worksheet can help connect those measures to runtime and shot planning.

How to interpret changes

First classify the failure before changing the tolerance. A structural diff suggests a circuit or compiler change. A simulator-only failure may indicate altered basis ordering, parameter binding, random-number handling, or an SDK result format. A noisy-simulator failure often points to a changed noise model or mitigation configuration. A hardware-only failure may reflect calibration drift, readout behavior, queue-time conditions, or provider integration.

Compare the same circuit across three stages when possible: the original logical circuit, the transpiled circuit, and the executed result. If the logical invariant holds but the transpiled circuit exceeds a depth budget, investigate compilation. If the ideal simulator passes and the noisy result shifts, compare the noise assumptions before modifying application code.

For probabilistic failures, rerun with the same seed and then with several seeds. A failure that disappears across seeds may be sampling variance. A failure that persists with more shots is more likely to be a real semantic or noise regression. Never widen a tolerance solely to make CI green; document the physical or statistical reason for the new threshold.

For variational or quantum machine learning workflows, test data preparation, parameter binding, objective evaluation, and optimization separately. Compare against a classical baseline and use fixed evaluation datasets where appropriate. The quantum machine learning evaluation guide covers reproducible metrics and split design that complement circuit-level tests.

When to revisit

Revisit this testing plan on a monthly or quarterly schedule and immediately after a major dependency, compiler, noise-model, or backend change. Also review it when a circuit gains parameters, moves from simulation to hardware, adopts error mitigation, changes measurement layout, or begins producing intermittent results.

Use this practical checklist:

  • Can a new contributor run fast tests without cloud credentials?
  • Does every probabilistic assertion state its shot count and tolerance?
  • Are seeds recorded but not mistaken for hardware guarantees?
  • Do tests distinguish logical-circuit behavior from transpiled-circuit behavior?
  • Are simulator and hardware jobs separated in CI?
  • Is each hardware failure accompanied by backend, SDK, timestamp, and execution metadata?
  • Have stale golden outputs and deprecated SDK calls been reviewed?

When upgrading Qiskit, Cirq, PennyLane, or a provider integration, run the full suite before changing expectations. When migrating simulators, consult the quantum simulator comparison guide and verify that the new simulator supports the same circuit features and noise assumptions. A modest, well-labeled regression suite is more valuable than a large collection of brittle snapshots: it tells you what changed, why it matters, and whether the change belongs in the circuit, the test, or the execution environment.

Related Topics

#quantum software testing#quantum circuit unit testing#CI/CD#regression testing#Qiskit#Cirq#PennyLane#pytest
S

Sharp Qbit Lab

Quantum Computing Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.