Testing Quantum Circuits in Python: Pytest Patterns for Simulators, Measurements, and CI
quantum testingPythonpytestQiskitCirqPennyLaneCI/CD

Testing Quantum Circuits in Python: Pytest Patterns for Simulators, Measurements, and CI

UUpQbit Labs
2026-11-14
7 min read

Use pytest to test quantum circuit structure, simulator states, measurement probabilities, backend boundaries, and CI workflows.

Reliable quantum software needs tests that verify circuit structure, ideal states, statistical measurements, and execution boundaries. This checklist shows how to use pytest with Qiskit, Cirq, and PennyLane so changes are caught in local development and continuous integration instead of being discovered by manually inspecting notebook output.

Overview

Quantum circuit testing is different from testing ordinary deterministic functions. A circuit can be structurally correct while its measured output varies from run to run. Conversely, a test may pass because it checks only one sampled result even though the circuit contains the wrong gate, qubit order, or measurement mapping.

A useful test suite separates four concerns:

  • Construction: Does the circuit contain the expected qubits, gates, parameters, and measurements?
  • Ideal behavior: Does a simulator produce the expected statevector or exact probability distribution?
  • Sampling behavior: Are shot-based results close enough to the expected probabilities?
  • Execution integration: Does application code submit the right circuit and interpret the returned result correctly?

Keep these tests small. A unit test should usually exercise one circuit-building function or one result-processing function. End-to-end tests can cover a complete workflow, but they should not be the only protection against a gate-order or qubit-index regression.

For Qiskit projects, pin and review the SDK versions used by the repository before copying examples into production. API boundaries around primitives, transpilation, and backends can change during migrations; the Qiskit 2.x migration guide is a useful companion when updating an existing codebase.

Checklist by scenario

1. Test circuit construction first

Start with assertions that do not involve randomness. For example, a Bell-state builder should create two qubits, apply a Hadamard to the first qubit, apply a controlled-NOT, and add measurements only when the caller requests them.

from qiskit import QuantumCircuit


def bell_circuit(measure=False):
    circuit = QuantumCircuit(2, 2 if measure else 0)
    circuit.h(0)
    circuit.cx(0, 1)
    if measure:
        circuit.measure([0, 1], [0, 1])
    return circuit


def test_bell_structure():
    circuit = bell_circuit()

    assert circuit.num_qubits == 2
    assert circuit.num_clbits == 0
    assert circuit.count_ops().get("h", 0) == 1
    assert circuit.count_ops().get("cx", 0) == 1


def test_bell_measurements_are_explicit():
    circuit = bell_circuit(measure=True)

    assert circuit.num_clbits == 2
    assert circuit.count_ops().get("measure", 0) == 2

These checks are intentionally specific. Testing only that the circuit is nonempty will not catch a missing entangling gate or an accidental measurement inserted before the computation.

2. Check ideal statevectors without shots

When the expected state is known, use an exact or near-exact simulator test. In Qiskit, Statevector.from_instruction evaluates a circuit without measurement instructions.

import numpy as np
from qiskit.quantum_info import Statevector


def test_bell_statevector():
    state = Statevector.from_instruction(bell_circuit())
    expected = np.array([1, 0, 0, 1]) / np.sqrt(2)

    assert np.allclose(state.data, expected)

Use numerical tolerances rather than comparing floating-point arrays with ==. Also confirm the SDK's basis-state and qubit-order conventions before writing the expected vector. A mathematically correct assertion can still be wrong if the test assumes a different bit ordering.

3. Test measurement probabilities with tolerances

Shot-based tests should assert a range, not an exact count. For a Bell circuit, outcomes 00 and 11 should each be close to one half, while 01 and 10 should be near zero. The exact range depends on the shot count and how much variability the test can reasonably tolerate.

from qiskit_aer import AerSimulator
from qiskit import transpile


def test_bell_measurement_distribution():
    simulator = AerSimulator(seed_simulator=1234)
    compiled = transpile(bell_circuit(measure=True), simulator)
    result = simulator.run(compiled, shots=2000).result()
    counts = result.get_counts()

    assert counts.get("00", 0) / 2000 == pytest.approx(0.5, abs=0.08)
    assert counts.get("11", 0) / 2000 == pytest.approx(0.5, abs=0.08)
    assert counts.get("01", 0) == 0
    assert counts.get("10", 0) == 0

Add import pytest to the test module. Seeding makes simulator tests reproducible, but it does not turn sampling into a deterministic mathematical guarantee. Keep the tolerance wide enough to avoid false failures and narrow enough to catch meaningful regressions.

Parameterized tests are useful for gates and small algorithms with predictable outcomes. The following pattern checks that an X gate flips the selected computational basis state.

import pytest
from qiskit.quantum_info import Statevector


@pytest.mark.parametrize("qubit", [0, 1])
def test_x_gate_flips_selected_qubit(qubit):
    circuit = QuantumCircuit(2)
    circuit.x(qubit)
    state = Statevector.from_instruction(circuit)

    probabilities = state.probabilities_dict()
    expected = "01" if qubit == 0 else "10"
    assert probabilities == {expected: 1.0}

Use a small table of cases for different input states, parameter values, wire counts, or measurement settings. This exposes indexing errors without duplicating complete test functions.

5. Apply the same ideas in Cirq and PennyLane

In Cirq, test the circuit object separately from simulation. A simple state-vector assertion can use the framework's simulator:

import cirq
import numpy as np


def test_cirq_x_gate():
    qubit = cirq.LineQubit(0)
    circuit = cirq.Circuit(cirq.X(qubit))
    result = cirq.Simulator().simulate(circuit)

    assert np.allclose(result.final_state_vector, [0, 1])

In PennyLane, a deterministic QNode can return probabilities when the device has no finite-shot setting:

import pennylane as qml


def test_pennylane_x_probability():
    dev = qml.device("default.qubit", wires=1)

    @qml.qnode(dev)
    def circuit():
        qml.PauliX(wires=0)
        return qml.probs(wires=0)

    assert circuit().tolist() == [0.0, 1.0]

For all three SDKs, keep simulator tests independent from cloud credentials and network access. Hardware or remote-backend checks belong in a separate integration job with explicit cost, availability, and failure handling.

6. Mock the backend boundary

Application code should pass a circuit to a narrow execution function rather than constructing, submitting, and parsing everything in one large function. Then use unittest.mock or pytest's monkeypatch fixture to return a controlled result. Assert that the expected circuit, shot count, and backend options were supplied. This tests your integration code without depending on a live service.

What to double-check

  • Qubit and classical-bit order: Verify how the SDK formats basis states and count keys before setting expected strings.
  • Measurements: Do not feed a circuit containing measurements into an API that expects a statevector unless the test deliberately covers that error.
  • Seeds: Set simulator seeds where supported, but do not rely on a seed to hide an overly strict assertion.
  • Floating-point comparisons: Use pytest.approx or NumPy's comparison helpers for amplitudes, gradients, and probabilities.
  • Transpilation: Test logical circuit intent separately from transpiled gate counts. A compiler may legally rewrite a circuit while preserving its behavior.
  • Noise: Keep ideal, noisy-simulator, and hardware tests distinct. Their expected distributions and tolerances should not be interchangeable.
  • Dependency versions: Run the suite in the same Python and SDK environments used by CI. Record simulator extras such as Qiskit Aer in project dependencies rather than assuming they are installed.

Common mistakes

Checking only that a job completed. A successful submission does not prove that the circuit or result interpretation is correct. Assert meaningful counts, probabilities, or state properties.

Expecting exact shot counts. Even a correct circuit can produce different samples. Test proportions with a documented tolerance.

Testing implementation details too aggressively. Gate-count assertions are valuable for a circuit builder, but they can make tests brittle after valid optimization. Pair structural tests with behavior tests.

Mixing unit and remote tests. A test that needs credentials, a queue, or a network connection is not a fast unit test. Mark it separately and keep pull-request checks dependable.

Ignoring failure diagnostics. When an assertion fails, print or report the full counts, probabilities, circuit diagram, shot count, seed, and SDK versions. These details shorten debugging time considerably.

When to revisit

Revisit this checklist whenever you add a gate, change qubit indexing, introduce parameterized ansatz code, alter measurement parsing, switch simulators, or move from local execution to a cloud backend. Also review it before preparing a repository for automated builds and during regular dependency updates, such as a twice-yearly SDK review.

A practical project layout keeps tests easy to find:

quantum-project/
├── src/quantum_project/
│   ├── circuits.py
│   └── execution.py
├── tests/
│   ├── test_circuits.py
│   ├── test_measurements.py
│   └── test_execution.py
├── pyproject.toml
└── .github/workflows/ci.yml

In CI, install the locked development dependencies, run fast simulator tests on every change, and reserve marked integration or hardware tests for an intentional workflow. A final pre-merge checklist is: inspect circuit structure, verify ideal behavior, test sampled probabilities with tolerances, seed where supported, cover representative parameters, mock remote execution, and record the versions used by the test job. This workflow makes quantum computing tutorials and Python quantum projects easier to extend without turning every simulator change into a manual investigation.

Related Topics

#quantum testing#Python#pytest#Qiskit#Cirq#PennyLane#CI/CD
U

UpQbit Labs

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.