diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 1ba476ce4b9..9e6a9d1c6d4 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,9 +1,9 @@ # How to Contribute We'd love to accept your patches and contributions to this project. -We do have some guidelines to follow, covered in this document, but don't +We do have some guidelines to follow, covered in this document, but don't worry about (or expect to) get everything right the first time! -Create a pull request and we'll nudge you in the right direction. Please also +Create a pull request and we'll nudge you in the right direction. Please also note that we have a [code of conduct](CODE_OF_CONDUCT.md) to make Cirq an open and welcoming environment. @@ -83,7 +83,7 @@ on setting up your local development environment. ## Code Testing Standards -When a pull request is created or updated, various automatic checks will +When a pull request is created or updated, various automatic checks will run to ensure that the change won't break Cirq and meets our coding standards. Cirq contains a continuous integration tool to verify testing. See our @@ -94,36 +94,36 @@ Please be aware of the following code standards that will be applied to any new changes. - **Tests**. -Existing tests must continue to pass (or be updated) when new changes are -introduced. We use [pytest](https://docs.pytest.org/en/latest/) to run our +Existing tests must continue to pass (or be updated) when new changes are +introduced. We use [pytest](https://docs.pytest.org/en/latest/) to run our tests. - **Coverage**. Code should be covered by tests. -We use [pytest-cov](https://pytest-cov.readthedocs.io/en/latest/) to compute +We use [pytest-cov](https://pytest-cov.readthedocs.io/en/latest/) to compute coverage, and custom tooling to filter down the output to only include new or -changed code. We don't require 100% coverage, but any uncovered code must -be annotated with `# coverage: ignore`. To ignore coverage of a single line, -place `# coverage: ignore` at the end of the line. To ignore coverage for -an entire block, start the block with a `# coverage: ignore` comment on its +changed code. We don't require 100% coverage, but any uncovered code must +be annotated with `# pragma: no cover`. To ignore coverage of a single line, +place `# pragma: no cover` at the end of the line. To ignore coverage for +an entire block, start the block with a `# pragma: no cover` comment on its own line. - **Lint**. -Code should meet common style standards for python and be free of error-prone +Code should meet common style standards for python and be free of error-prone constructs. We use [pylint](https://www.pylint.org/) to check for lint. -To see which lint checks we enforce, see the +To see which lint checks we enforce, see the [dev_tools/conf/.pylintrc](dev_tools/conf/.pylintrc) file. When pylint produces -a false positive, it can be squashed with annotations like +a false positive, it can be squashed with annotations like `# pylint: disable=unused-import`. - **Types**. Code should have [type annotations](https://www.python.org/dev/peps/pep-0484/). We use [mypy](http://mypy-lang.org/) to check that type annotations are correct. -When type checking produces a false positive, it can be ignored with +When type checking produces a false positive, it can be ignored with annotations like `# type: ignore`. ## Request For Comment Process for New Major Features -For larger contributions that will benefit from design reviews, please use the +For larger contributions that will benefit from design reviews, please use the [Request for Comment](docs/dev/rfc_process.md) process. -## Developing notebooks +## Developing notebooks -Please refer to our [notebooks guide](docs/dev/notebooks.md) on how to develop iPython notebooks for documentation. \ No newline at end of file +Please refer to our [notebooks guide](docs/dev/notebooks.md) on how to develop iPython notebooks for documentation. diff --git a/cirq-core/cirq/_version.py b/cirq-core/cirq/_version.py index dae8a271d9d..2928a84c448 100644 --- a/cirq-core/cirq/_version.py +++ b/cirq-core/cirq/_version.py @@ -17,8 +17,7 @@ import sys -if sys.version_info < (3, 9, 0): - # coverage: ignore +if sys.version_info < (3, 9, 0): # pragma: no cover raise SystemError( "You installed the latest version of cirq but aren't on python 3.9+.\n" 'To fix this error, you need to either:\n' diff --git a/cirq-core/cirq/circuits/circuit_operation.py b/cirq-core/cirq/circuits/circuit_operation.py index 9f81a33714b..539e3fe2003 100644 --- a/cirq-core/cirq/circuits/circuit_operation.py +++ b/cirq-core/cirq/circuits/circuit_operation.py @@ -61,9 +61,9 @@ def _full_join_string_lists( list1: Optional[Sequence[str]], list2: Optional[Sequence[str]] ) -> Optional[Sequence[str]]: if list1 is None and list2 is None: - return None # coverage: ignore + return None # pragma: no cover if list1 is None: - return list2 # coverage: ignore + return list2 # pragma: no cover if list2 is None: return list1 return [f'{first}{REPETITION_ID_SEPARATOR}{second}' for first in list1 for second in list2] diff --git a/cirq-core/cirq/circuits/qasm_output_test.py b/cirq-core/cirq/circuits/qasm_output_test.py index ac2c06c35c9..43b23388b49 100644 --- a/cirq-core/cirq/circuits/qasm_output_test.py +++ b/cirq-core/cirq/circuits/qasm_output_test.py @@ -257,7 +257,7 @@ def _qasm_(self, args: cirq.QasmArgs) -> str: def _decompose_(self): # Only used by test_output_unitary_same_as_qiskit - return () # coverage: ignore + return () # pragma: no cover class DummyCompositeOperation(cirq.Operation): qubits = (q0,) diff --git a/cirq-core/cirq/conftest.py b/cirq-core/cirq/conftest.py index c871dd5182e..7991723c145 100644 --- a/cirq-core/cirq/conftest.py +++ b/cirq-core/cirq/conftest.py @@ -27,8 +27,7 @@ def pytest_configure(config): def pytest_pyfunc_call(pyfuncitem): if inspect.iscoroutinefunction(pyfuncitem._obj): - # coverage: ignore - raise ValueError( + raise ValueError( # pragma: no cover f'{pyfuncitem._obj.__name__} is a bare async function. ' f'It should be decorated with "@duet.sync".' ) diff --git a/cirq-core/cirq/contrib/acquaintance/devices.py b/cirq-core/cirq/contrib/acquaintance/devices.py index f40dedb1dd9..dff29fd08c9 100644 --- a/cirq-core/cirq/contrib/acquaintance/devices.py +++ b/cirq-core/cirq/contrib/acquaintance/devices.py @@ -68,7 +68,7 @@ class _UnconstrainedAcquaintanceDevice(AcquaintanceDevice): """An acquaintance device with no constraints other than of the gate types.""" def __repr__(self) -> str: - return 'UnconstrainedAcquaintanceDevice' # coverage: ignore + return 'UnconstrainedAcquaintanceDevice' # pragma: no cover UnconstrainedAcquaintanceDevice = _UnconstrainedAcquaintanceDevice() diff --git a/cirq-core/cirq/contrib/hacks/disable_validation_test.py b/cirq-core/cirq/contrib/hacks/disable_validation_test.py index 6cb5808417c..786ad7f2120 100644 --- a/cirq-core/cirq/contrib/hacks/disable_validation_test.py +++ b/cirq-core/cirq/contrib/hacks/disable_validation_test.py @@ -29,7 +29,7 @@ def test_disable_op_validation(): with pytest.raises(ValueError, match='mysterious and terrible'): with disable_op_validation(): # This does not run - the with condition errors out first. - _ = cirq.H(q0, q1) # coverage: ignore + _ = cirq.H(q0, q1) # pragma: no cover # Passes, skipping validation. with disable_op_validation(accept_debug_responsibility=True): diff --git a/cirq-core/cirq/contrib/noise_models/noise_models.py b/cirq-core/cirq/contrib/noise_models/noise_models.py index 8d179d2348c..82653d99065 100644 --- a/cirq-core/cirq/contrib/noise_models/noise_models.py +++ b/cirq-core/cirq/contrib/noise_models/noise_models.py @@ -41,8 +41,7 @@ def __init__(self, depol_prob: float, prepend: bool = False): self._prepend = prepend def noisy_moment(self, moment: 'cirq.Moment', system_qubits: Sequence['cirq.Qid']): - if validate_all_measurements(moment) or self.is_virtual_moment(moment): - # coverage: ignore + if validate_all_measurements(moment) or self.is_virtual_moment(moment): # pragma: no cover return moment output = [ diff --git a/cirq-core/cirq/contrib/paulistring/clifford_optimize.py b/cirq-core/cirq/contrib/paulistring/clifford_optimize.py index a28992fee5d..fd43f5f0e2b 100644 --- a/cirq-core/cirq/contrib/paulistring/clifford_optimize.py +++ b/cirq-core/cirq/contrib/paulistring/clifford_optimize.py @@ -161,7 +161,7 @@ def try_merge_cz(cz_op: ops.GateOperation, start_i: int) -> int: else: # Two CZ gates that share one qubit # Pass through and keep looking - continue # coverage: ignore + continue # pragma: no cover # The above line is covered by test_remove_staggered_czs but the # coverage checker disagrees. return 0 diff --git a/cirq-core/cirq/contrib/qcircuit/qcircuit_pdf.py b/cirq-core/cirq/contrib/qcircuit/qcircuit_pdf.py index 9d3955c63c0..a91282fef6e 100644 --- a/cirq-core/cirq/contrib/qcircuit/qcircuit_pdf.py +++ b/cirq-core/cirq/contrib/qcircuit/qcircuit_pdf.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -# coverage: ignore +# pragma: no cover import errno import os diff --git a/cirq-core/cirq/contrib/quimb/density_matrix.py b/cirq-core/cirq/contrib/quimb/density_matrix.py index 05acff4aa15..441c04738d0 100644 --- a/cirq-core/cirq/contrib/quimb/density_matrix.py +++ b/cirq-core/cirq/contrib/quimb/density_matrix.py @@ -106,8 +106,7 @@ def circuit_to_density_matrix_tensors( ValueError: If an op is encountered that cannot be converted. """ if qubits is None: - # coverage: ignore - qubits = sorted(circuit.all_qubits()) + qubits = sorted(circuit.all_qubits()) # pragma: no cover qubits = tuple(qubits) qubit_frontier: Dict[cirq.Qid, int] = {q: 0 for q in qubits} @@ -190,7 +189,7 @@ def _positions(_mi, _these_qubits): ) kraus_frontier += 1 else: - raise ValueError(repr(op)) # coverage: ignore + raise ValueError(repr(op)) # pragma: no cover _positions(mi + 1, op.qubits) return tensors, qubit_frontier, positions diff --git a/cirq-core/cirq/contrib/quimb/grid_circuits.py b/cirq-core/cirq/contrib/quimb/grid_circuits.py index 432e793d44b..4f64b9fe9a5 100644 --- a/cirq-core/cirq/contrib/quimb/grid_circuits.py +++ b/cirq-core/cirq/contrib/quimb/grid_circuits.py @@ -54,12 +54,12 @@ def _interaction( for col in range(col_start + col_start_offset, col_end + col_end_offset, col_step): node1 = (row, col) if node1 not in problem_graph.nodes: - continue # coverage: ignore + continue # pragma: no cover node2 = get_neighbor(row, col) if node2 not in problem_graph.nodes: - continue # coverage: ignore + continue # pragma: no cover if (node1, node2) not in problem_graph.edges: - continue # coverage: ignore + continue # pragma: no cover weight = problem_graph.edges[node1, node2].get('weight', 1) yield two_qubit_gate(exponent=weight, global_shift=-0.5).on( diff --git a/cirq-core/cirq/contrib/quimb/state_vector.py b/cirq-core/cirq/contrib/quimb/state_vector.py index aaea1340bce..d04e7a8f159 100644 --- a/cirq-core/cirq/contrib/quimb/state_vector.py +++ b/cirq-core/cirq/contrib/quimb/state_vector.py @@ -9,7 +9,6 @@ import cirq -# coverage: ignore def _get_quimb_version(): """Returns the quimb version and parsed (major,minor) numbers if possible. Returns: @@ -18,7 +17,7 @@ def _get_quimb_version(): version = quimb.__version__ try: return tuple(int(x) for x in version.split('.')), version - except: + except: # pragma: no cover return (0, 0), version @@ -59,7 +58,7 @@ def circuit_to_tensors( corresponding to the |0> state. """ if qubits is None: - qubits = sorted(circuit.all_qubits()) # coverage: ignore + qubits = sorted(circuit.all_qubits()) # pragma: no cover qubit_frontier = {q: 0 for q in qubits} positions = None @@ -163,8 +162,7 @@ def tensor_expectation_value( ] tn = qtn.TensorNetwork(tensors + end_bras) if QUIMB_VERSION[0] < (1, 3): - # coverage: ignore - warnings.warn( + warnings.warn( # pragma: no cover f'quimb version {QUIMB_VERSION[1]} detected. Please use ' f'quimb>=1.3 for optimal performance in ' '`tensor_expectation_value`. ' diff --git a/cirq-core/cirq/contrib/routing/utils.py b/cirq-core/cirq/contrib/routing/utils.py index 5627261ee3f..72a545ba13a 100644 --- a/cirq-core/cirq/contrib/routing/utils.py +++ b/cirq-core/cirq/contrib/routing/utils.py @@ -96,8 +96,7 @@ def get_circuit_connectivity(circuit: 'cirq.Circuit') -> nx.Graph: for op in circuit.all_operations(): n_qubits = len(op.qubits) if n_qubits > 2: - # coverage: ignore - raise ValueError( + raise ValueError( # pragma: no cover f"Cannot build a graph out of a circuit that " f"contains {n_qubits}-qubit operations" ) diff --git a/cirq-core/cirq/contrib/svg/svg.py b/cirq-core/cirq/contrib/svg/svg.py index d4043347346..be7a1d60c56 100644 --- a/cirq-core/cirq/contrib/svg/svg.py +++ b/cirq-core/cirq/contrib/svg/svg.py @@ -140,12 +140,11 @@ def _fit_vertical( return row_starts, row_heights, yi_map -def _debug_spacing(col_starts, row_starts): +def _debug_spacing(col_starts, row_starts): # pragma: no cover """Return a string suitable for inserting inside an tag that draws green lines where columns and rows start. This is very useful if you're developing this code and are debugging spacing issues. """ - # coverage: ignore t = '' for i, cs in enumerate(col_starts): t += ( @@ -198,7 +197,6 @@ def tdd_to_svg( # qubits start at far left and their wires shall be blue stroke = QBLUE else: - # coverage: ignore stroke = 'black' t += f'' @@ -261,11 +259,9 @@ class SVGCircuit: """ def __init__(self, circuit: 'cirq.Circuit'): - # coverage: ignore self.circuit = circuit def _repr_svg_(self) -> str: - # coverage: ignore return circuit_to_svg(self.circuit) diff --git a/cirq-core/cirq/devices/named_topologies.py b/cirq-core/cirq/devices/named_topologies.py index abc81253031..5f32d8b1d5d 100644 --- a/cirq-core/cirq/devices/named_topologies.py +++ b/cirq-core/cirq/devices/named_topologies.py @@ -93,7 +93,7 @@ def draw_gridlike( to NetworkX plotting functionality. """ if ax is None: - ax = plt.gca() # coverage: ignore + ax = plt.gca() # pragma: no cover if tilted: pos = {node: (y, -x) for node, (x, y) in _node_and_coordinates(graph.nodes)} @@ -295,8 +295,7 @@ def get_placements( for big_to_small_map in matcher.subgraph_monomorphisms_iter(): dedupe[frozenset(big_to_small_map.keys())] = big_to_small_map if len(dedupe) > max_placements: - # coverage: ignore - raise ValueError( + raise ValueError( # pragma: no cover f"We found more than {max_placements} placements. Please use a " f"more constraining `big_graph` or a more constrained `small_graph`." ) @@ -367,27 +366,23 @@ def draw_placements( this callback is called. The callback should accept `ax` and `i` keyword arguments for the current axis and mapping index, respectively. """ - if len(small_to_big_mappings) > max_plots: - # coverage: ignore + if len(small_to_big_mappings) > max_plots: # pragma: no cover warnings.warn(f"You've provided a lot of mappings. Only plotting the first {max_plots}") small_to_big_mappings = small_to_big_mappings[:max_plots] call_show = False if axes is None: - # coverage: ignore - call_show = True + call_show = True # pragma: no cover for i, small_to_big_map in enumerate(small_to_big_mappings): if axes is not None: ax = axes[i] - else: - # coverage: ignore + else: # pragma: no cover ax = plt.gca() small_mapped = nx.relabel_nodes(small_graph, small_to_big_map) if bad_placement_callback is not None: - # coverage: ignore - if not _is_valid_placement_helper( + if not _is_valid_placement_helper( # pragma: no cover big_graph=big_graph, small_mapped=small_mapped, small_to_big_mapping=small_to_big_map, @@ -406,7 +401,6 @@ def draw_placements( ) ax.axis('equal') if call_show: - # coverage: ignore # poor man's multi-axis figure: call plt.show() after each plot # and jupyter will put the plots one after another. - plt.show() + plt.show() # pragma: no cover diff --git a/cirq-core/cirq/devices/noise_properties.py b/cirq-core/cirq/devices/noise_properties.py index 42fadb52757..5152d3c8169 100644 --- a/cirq-core/cirq/devices/noise_properties.py +++ b/cirq-core/cirq/devices/noise_properties.py @@ -97,7 +97,7 @@ def noisy_moments( # only ops with PHYSICAL_GATE_TAG will receive noise. if virtual_ops: # Only subclasses will trigger this case. - new_moments.append(circuits.Moment(virtual_ops)) # coverage: ignore + new_moments.append(circuits.Moment(virtual_ops)) # pragma: no cover if physical_ops: new_moments.append(circuits.Moment(physical_ops)) diff --git a/cirq-core/cirq/experiments/readout_confusion_matrix.py b/cirq-core/cirq/experiments/readout_confusion_matrix.py index 4fdc3c525ae..d99925aad14 100644 --- a/cirq-core/cirq/experiments/readout_confusion_matrix.py +++ b/cirq-core/cirq/experiments/readout_confusion_matrix.py @@ -278,7 +278,7 @@ def apply( raise ValueError(f"method: {method} should be 'pseudo_inverse' or 'least_squares'.") if method == 'pseudo_inverse': - return result @ self.correction_matrix(qubits) # coverage: ignore + return result @ self.correction_matrix(qubits) # pragma: no cover # Least squares minimization. cm = self.confusion_matrix(qubits) @@ -291,11 +291,11 @@ def func(x): res = scipy.optimize.minimize( func, result, method='SLSQP', constraints=constraints, bounds=bounds ) - if res.success is False: # coverage: ignore - raise ValueError( # coverage: ignore - f"SLSQP optimization for constrained minimization " # coverage: ignore - f"did not converge. Result:\n{res}" # coverage: ignore - ) # coverage: ignore + if res.success is False: # pragma: no cover + raise ValueError( # pragma: no cover + f"SLSQP optimization for constrained minimization " # pragma: no cover + f"did not converge. Result:\n{res}" # pragma: no cover + ) # pragma: no cover return res.x def __repr__(self) -> str: diff --git a/cirq-core/cirq/experiments/xeb_fitting.py b/cirq-core/cirq/experiments/xeb_fitting.py index d76a4c8445d..bbce3300b61 100644 --- a/cirq-core/cirq/experiments/xeb_fitting.py +++ b/cirq-core/cirq/experiments/xeb_fitting.py @@ -108,12 +108,11 @@ def per_cycle_depth(df): def _try_keep(k): """If all the values for a key `k` are the same in this group, we can keep it.""" if k not in df.columns: - return # coverage: ignore + return # pragma: no cover vals = df[k].unique() if len(vals) == 1: ret[k] = vals[0] - else: - # coverage: ignore + else: # pragma: no cover raise AssertionError( f"When computing per-cycle-depth fidelity, multiple " f"values for {k} were grouped together: {vals}" @@ -574,8 +573,7 @@ def _fit_exponential_decay( p0=(a_0, layer_fid_0), bounds=((0, 0), (1, 1)), ) - except ValueError: # coverage: ignore - # coverage: ignore + except ValueError: # pragma: no cover return 0, 0, np.inf, np.inf a_std, layer_fid_std = np.sqrt(np.diag(pcov)) diff --git a/cirq-core/cirq/ops/classically_controlled_operation.py b/cirq-core/cirq/ops/classically_controlled_operation.py index 63725fe6b23..d4c53bdb367 100644 --- a/cirq-core/cirq/ops/classically_controlled_operation.py +++ b/cirq-core/cirq/ops/classically_controlled_operation.py @@ -155,7 +155,7 @@ def _circuit_diagram_info_( ) sub_info = protocols.circuit_diagram_info(self._sub_operation, sub_args, None) if sub_info is None: - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover control_label_count = 0 if args.label_map is not None: control_label_count = len({k for c in self._conditions for k in c.keys}) diff --git a/cirq-core/cirq/ops/clifford_gate.py b/cirq-core/cirq/ops/clifford_gate.py index 7a53b40ee4b..7743b5d20cf 100644 --- a/cirq-core/cirq/ops/clifford_gate.py +++ b/cirq-core/cirq/ops/clifford_gate.py @@ -448,7 +448,7 @@ def _act_on_( sim_state._state = sim_state.tableau.then(padded_tableau) return True - if isinstance(sim_state, sim.clifford.StabilizerChFormSimulationState): # coverage: ignore + if isinstance(sim_state, sim.clifford.StabilizerChFormSimulationState): # pragma: no cover # Do we know how to apply CliffordTableau on StabilizerChFormSimulationState? # It should be unlike because CliffordTableau ignores the global phase but CHForm # is aimed to fix that. @@ -846,8 +846,7 @@ def decompose_rotation(self) -> Sequence[Tuple[Pauli, int]]: ] return [(pauli_gates.Z, 1 if y_rot[1] else -1), (pauli_gates.X, 1 if z_rot[1] else -1)] - # coverage: ignore - assert ( + assert ( # pragma: no cover False ), 'Impossible condition where this gate only rotates one Pauli to a different Pauli.' diff --git a/cirq-core/cirq/ops/controlled_operation_test.py b/cirq-core/cirq/ops/controlled_operation_test.py index 5be0617ca87..1f1cb3a2531 100644 --- a/cirq-core/cirq/ops/controlled_operation_test.py +++ b/cirq-core/cirq/ops/controlled_operation_test.py @@ -446,10 +446,10 @@ def test_controlled_operation_gate(): class Gateless(cirq.Operation): @property def qubits(self): - return () # coverage: ignore + return () # pragma: no cover def with_qubits(self, *new_qubits): - return self # coverage: ignore + return self # pragma: no cover def _has_mixture_(self): return True diff --git a/cirq-core/cirq/ops/eigen_gate_test.py b/cirq-core/cirq/ops/eigen_gate_test.py index 47d9a06a804..7611d7ba4ee 100644 --- a/cirq-core/cirq/ops/eigen_gate_test.py +++ b/cirq-core/cirq/ops/eigen_gate_test.py @@ -201,8 +201,7 @@ def test_trace_distance_bound(): assert cirq.approx_eq(cirq.trace_distance_bound(CExpZinGate(2)), 1) class E(cirq.EigenGate): - def _num_qubits_(self): - # coverage: ignore + def _num_qubits_(self): # pragma: no cover return 1 def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: @@ -227,7 +226,6 @@ def test_extrapolate(): def test_matrix(): - for n in [1, 2, 3, 4, 0.0001, 3.9999]: assert cirq.has_unitary(CExpZinGate(n)) diff --git a/cirq-core/cirq/ops/fourier_transform.py b/cirq-core/cirq/ops/fourier_transform.py index e98331aeeba..6b7be5caf70 100644 --- a/cirq-core/cirq/ops/fourier_transform.py +++ b/cirq-core/cirq/ops/fourier_transform.py @@ -146,8 +146,7 @@ def _apply_unitary_(self, args: 'cirq.ApplyUnitaryArgs'): def __pow__(self, power): new_exponent = cirq.mul(self.exponent, power, NotImplemented) - if new_exponent is NotImplemented: - # coverage: ignore + if new_exponent is NotImplemented: # pragma: no cover return NotImplemented return PhaseGradientGate(num_qubits=self._num_qubits, exponent=new_exponent) diff --git a/cirq-core/cirq/ops/gate_operation_test.py b/cirq-core/cirq/ops/gate_operation_test.py index bce07dce0e9..46cf3cae1a5 100644 --- a/cirq-core/cirq/ops/gate_operation_test.py +++ b/cirq-core/cirq/ops/gate_operation_test.py @@ -523,8 +523,7 @@ def all_subclasses(cls): if gate_cls in skip_classes: skipped.add(gate_cls) continue - # coverage:ignore - raise AssertionError( + raise AssertionError( # pragma: no cover f"{gate_cls} has no json file, please add a json file or add to the list of " "classes to be skipped if there is a reason this gate should not round trip " "to a gate via creating an operation." diff --git a/cirq-core/cirq/ops/pauli_gates.py b/cirq-core/cirq/ops/pauli_gates.py index f8ea35f1c63..3af55eef5ed 100644 --- a/cirq-core/cirq/ops/pauli_gates.py +++ b/cirq-core/cirq/ops/pauli_gates.py @@ -26,7 +26,7 @@ _XEigenState, _YEigenState, _ZEigenState, - ) # coverage: ignore + ) # pragma: no cover class Pauli(raw_types.Gate, metaclass=abc.ABCMeta): diff --git a/cirq-core/cirq/ops/pauli_string.py b/cirq-core/cirq/ops/pauli_string.py index de90b0fe327..21ce7be0dac 100644 --- a/cirq-core/cirq/ops/pauli_string.py +++ b/cirq-core/cirq/ops/pauli_string.py @@ -92,7 +92,7 @@ """, ) -PAULI_GATE_LIKE = Union['cirq.Pauli', 'cirq.IdentityGate', str, int,] +PAULI_GATE_LIKE = Union['cirq.Pauli', 'cirq.IdentityGate', str, int] document( PAULI_GATE_LIKE, """An object that can be interpreted as a Pauli gate. @@ -1387,8 +1387,7 @@ def inplace_after(self, ops: 'cirq.OP_TREE') -> 'cirq.MutablePauliString': if gate.invert1: self.inplace_after(gate.pauli0(q0)) - else: - # coverage: ignore + else: # pragma: no cover raise NotImplementedError(f"Unrecognized decomposed Clifford: {op!r}") return self @@ -1617,7 +1616,7 @@ def _pass_single_clifford_gate_over( after_to_before: bool = False, ) -> bool: if qubit not in pauli_map: - return False # coverage: ignore + return False # pragma: no cover if not after_to_before: gate **= -1 pauli, inv = gate.pauli_tuple(pauli_map[qubit]) diff --git a/cirq-core/cirq/ops/pauli_string_test.py b/cirq-core/cirq/ops/pauli_string_test.py index 40b82fb65a0..7c01c2355c6 100644 --- a/cirq-core/cirq/ops/pauli_string_test.py +++ b/cirq-core/cirq/ops/pauli_string_test.py @@ -1765,8 +1765,7 @@ def __init__(self, *qubits): self._qubits = qubits @property - def qubits(self): - # coverage: ignore + def qubits(self): # pragma: no cover return self._qubits def with_qubits(self, *new_qubits): diff --git a/cirq-core/cirq/ops/raw_types.py b/cirq-core/cirq/ops/raw_types.py index 9366254581b..7739f2d268e 100644 --- a/cirq-core/cirq/ops/raw_types.py +++ b/cirq-core/cirq/ops/raw_types.py @@ -671,7 +671,7 @@ def _commutes_( # Don't create gigantic matrices. shape = protocols.qid_shape_protocol.qid_shape(circuit12) if np.prod(shape, dtype=np.int64) > 2**10: - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover m12 = protocols.unitary_protocol.unitary(circuit12, default=None) m21 = protocols.unitary_protocol.unitary(circuit21, default=None) diff --git a/cirq-core/cirq/ops/raw_types_test.py b/cirq-core/cirq/ops/raw_types_test.py index 844d44610c5..384d45b2658 100644 --- a/cirq-core/cirq/ops/raw_types_test.py +++ b/cirq-core/cirq/ops/raw_types_test.py @@ -356,7 +356,7 @@ def _qid_shape_(self): def test_operation_shape(): class FixedQids(cirq.Operation): def with_qubits(self, *new_qids): - raise NotImplementedError # coverage: ignore + raise NotImplementedError # pragma: no cover class QubitOp(FixedQids): @property diff --git a/cirq-core/cirq/protocols/has_stabilizer_effect_protocol_test.py b/cirq-core/cirq/protocols/has_stabilizer_effect_protocol_test.py index d54d00db305..e50124d0eab 100644 --- a/cirq-core/cirq/protocols/has_stabilizer_effect_protocol_test.py +++ b/cirq-core/cirq/protocols/has_stabilizer_effect_protocol_test.py @@ -49,11 +49,9 @@ class EmptyOp(cirq.Operation): @property def qubits(self): - # coverage: ignore return (q,) - def with_qubits(self, *new_qubits): - # coverage: ignore + def with_qubits(self, *new_qubits): # pragma: no cover return self diff --git a/cirq-core/cirq/protocols/has_unitary_protocol_test.py b/cirq-core/cirq/protocols/has_unitary_protocol_test.py index a91d3d971be..3c4082df8aa 100644 --- a/cirq-core/cirq/protocols/has_unitary_protocol_test.py +++ b/cirq-core/cirq/protocols/has_unitary_protocol_test.py @@ -213,9 +213,7 @@ class EmptyOp(cirq.Operation): @property def qubits(self): - # coverage: ignore return () - def with_qubits(self, *new_qubits): - # coverage: ignore + def with_qubits(self, *new_qubits): # pragma: no cover return self diff --git a/cirq-core/cirq/protocols/json_serialization.py b/cirq-core/cirq/protocols/json_serialization.py index c9ffea4c1d3..e4dc10d8ecb 100644 --- a/cirq-core/cirq/protocols/json_serialization.py +++ b/cirq-core/cirq/protocols/json_serialization.py @@ -303,7 +303,7 @@ def default(self, o): if isinstance(o, datetime.datetime): return {'cirq_type': 'datetime.datetime', 'timestamp': o.timestamp()} - return super().default(o) # coverage: ignore + return super().default(o) # pragma: no cover def _cirq_object_hook(d, resolvers: Sequence[JsonResolver], context_map: Dict[str, Any]): @@ -631,7 +631,7 @@ def default(self, o): return _json_dict_with_cirq_type(candidate.obj) else: return _json_dict_with_cirq_type(_SerializedKey(candidate.key)) - raise ValueError("Object mutated during serialization.") # coverage: ignore + raise ValueError("Object mutated during serialization.") # pragma: no cover cls = ContextualEncoder diff --git a/cirq-core/cirq/protocols/json_serialization_test.py b/cirq-core/cirq/protocols/json_serialization_test.py index de1d991915f..d25aa8a0938 100644 --- a/cirq-core/cirq/protocols/json_serialization_test.py +++ b/cirq-core/cirq/protocols/json_serialization_test.py @@ -489,8 +489,7 @@ def test_json_test_data_coverage(mod_spec: ModuleJsonTestSpec, cirq_obj_name: st json_path2 = test_data_path / f'{cirq_obj_name}.json_inward' deprecation_deadline = mod_spec.deprecated.get(cirq_obj_name) - if not json_path.exists() and not json_path2.exists(): - # coverage: ignore + if not json_path.exists() and not json_path2.exists(): # pragma: no cover pytest.fail( f"Hello intrepid developer. There is a new public or " f"serializable object named '{cirq_obj_name}' in the module '{mod_spec.name}' " @@ -634,10 +633,9 @@ def test_to_from_json_gzip(): def _eval_repr_data_file(path: pathlib.Path, deprecation_deadline: Optional[str]): content = path.read_text() ctx_managers: List[contextlib.AbstractContextManager] = [contextlib.suppress()] - if deprecation_deadline: + if deprecation_deadline: # pragma: no cover # we ignore coverage here, because sometimes there are no deprecations at all in any of the # modules - # coverage: ignore ctx_managers = [cirq.testing.assert_deprecated(deadline=deprecation_deadline, count=None)] for deprecation in TESTED_MODULES.values(): @@ -681,12 +679,10 @@ def assert_repr_and_json_test_data_agree( ) with ctx_manager: json_obj = cirq.read_json(json_text=json_from_file) - except ValueError as ex: # coverage: ignore - # coverage: ignore + except ValueError as ex: # pragma: no cover if "Could not resolve type" in str(ex): mod_path = mod_spec.name.replace(".", "/") rel_resolver_cache_path = f"{mod_path}/json_resolver_cache.py" - # coverage: ignore pytest.fail( f"{rel_json_path} can't be parsed to JSON.\n" f"Maybe an entry is missing from the " @@ -694,17 +690,14 @@ def assert_repr_and_json_test_data_agree( ) else: raise ValueError(f"deprecation: {deprecation_deadline} - got error: {ex}") - except AssertionError as ex: # coverage: ignore - # coverage: ignore + except AssertionError as ex: # pragma: no cover raise ex - except Exception as ex: # coverage: ignore - # coverage: ignore + except Exception as ex: # pragma: no cover raise IOError(f'Failed to parse test json data from {rel_json_path}.') from ex try: repr_obj = _eval_repr_data_file(repr_path, deprecation_deadline) - except Exception as ex: # coverage: ignore - # coverage: ignore + except Exception as ex: # pragma: no cover raise IOError(f'Failed to parse test repr data from {rel_repr_path}.') from ex assert proper_eq(json_obj, repr_obj), ( diff --git a/cirq-core/cirq/protocols/measurement_key_protocol_test.py b/cirq-core/cirq/protocols/measurement_key_protocol_test.py index f07d032b986..c74edd1628d 100644 --- a/cirq-core/cirq/protocols/measurement_key_protocol_test.py +++ b/cirq-core/cirq/protocols/measurement_key_protocol_test.py @@ -146,7 +146,7 @@ def _measurement_key_objs_(self): assert False def num_qubits(self) -> int: - return 2 # coverage: ignore + return 2 # pragma: no cover assert not cirq.is_measurement(NonMeasurementGate()) diff --git a/cirq-core/cirq/protocols/unitary_protocol_test.py b/cirq-core/cirq/protocols/unitary_protocol_test.py index 5d972c082ce..15e9daa8274 100644 --- a/cirq-core/cirq/protocols/unitary_protocol_test.py +++ b/cirq-core/cirq/protocols/unitary_protocol_test.py @@ -64,7 +64,7 @@ def _unitary_(self) -> np.ndarray: return m1 def num_qubits(self): - return 1 # coverage: ignore + return 1 # pragma: no cover class FullyImplemented(cirq.Gate): @@ -209,7 +209,6 @@ def _test_gate_that_allocates_qubits(gate): def test_decompose_gate_that_allocates_clean_qubits( theta: float, phase_state: int, target_bitsize: int, ancilla_bitsize: int ): - gate = testing.PhaseUsingCleanAncilla(theta, phase_state, target_bitsize, ancilla_bitsize) _test_gate_that_allocates_qubits(gate) @@ -220,7 +219,6 @@ def test_decompose_gate_that_allocates_clean_qubits( def test_decompose_gate_that_allocates_dirty_qubits( phase_state: int, target_bitsize: int, ancilla_bitsize: int ): - gate = testing.PhaseUsingDirtyAncilla(phase_state, target_bitsize, ancilla_bitsize) _test_gate_that_allocates_qubits(gate) @@ -305,8 +303,7 @@ def __init__(self, q): def qubits(self): return (self.q,) - def with_qubits(self, *new_qubits): - # coverage: ignore + def with_qubits(self, *new_qubits): # pragma: no cover return ApplyOp(*new_qubits) def _apply_unitary_(self, args): diff --git a/cirq-core/cirq/qis/clifford_tableau.py b/cirq-core/cirq/qis/clifford_tableau.py index d278e050f41..f7f0d334eb4 100644 --- a/cirq-core/cirq/qis/clifford_tableau.py +++ b/cirq-core/cirq/qis/clifford_tableau.py @@ -275,8 +275,7 @@ def _validate(self) -> bool: def __eq__(self, other): if not isinstance(other, type(self)): - # coverage: ignore - return NotImplemented + return NotImplemented # pragma: no cover return ( self.n == other.n and np.array_equal(self.rs, other.rs) @@ -551,7 +550,7 @@ def apply_x(self, axis: int, exponent: float = 1, global_shift: float = 0): if exponent % 2 == 0: return if exponent % 0.5 != 0.0: - raise ValueError('X exponent must be half integer') # coverage: ignore + raise ValueError('X exponent must be half integer') # pragma: no cover effective_exponent = exponent % 2 if effective_exponent == 0.5: self.xs[:, axis] ^= self.zs[:, axis] @@ -566,7 +565,7 @@ def apply_y(self, axis: int, exponent: float = 1, global_shift: float = 0): if exponent % 2 == 0: return if exponent % 0.5 != 0.0: - raise ValueError('Y exponent must be half integer') # coverage: ignore + raise ValueError('Y exponent must be half integer') # pragma: no cover effective_exponent = exponent % 2 if effective_exponent == 0.5: self.rs[:] ^= self.xs[:, axis] & (~self.zs[:, axis]) @@ -587,7 +586,7 @@ def apply_z(self, axis: int, exponent: float = 1, global_shift: float = 0): if exponent % 2 == 0: return if exponent % 0.5 != 0.0: - raise ValueError('Z exponent must be half integer') # coverage: ignore + raise ValueError('Z exponent must be half integer') # pragma: no cover effective_exponent = exponent % 2 if effective_exponent == 0.5: self.rs[:] ^= self.xs[:, axis] & self.zs[:, axis] @@ -602,7 +601,7 @@ def apply_h(self, axis: int, exponent: float = 1, global_shift: float = 0): if exponent % 2 == 0: return if exponent % 1 != 0: - raise ValueError('H exponent must be integer') # coverage: ignore + raise ValueError('H exponent must be integer') # pragma: no cover self.apply_y(axis, 0.5) self.apply_x(axis) @@ -612,7 +611,7 @@ def apply_cz( if exponent % 2 == 0: return if exponent % 1 != 0: - raise ValueError('CZ exponent must be integer') # coverage: ignore + raise ValueError('CZ exponent must be integer') # pragma: no cover (self.xs[:, target_axis], self.zs[:, target_axis]) = ( self.zs[:, target_axis].copy(), self.xs[:, target_axis].copy(), @@ -637,7 +636,7 @@ def apply_cx( if exponent % 2 == 0: return if exponent % 1 != 0: - raise ValueError('CX exponent must be integer') # coverage: ignore + raise ValueError('CX exponent must be integer') # pragma: no cover self.rs[:] ^= ( self.xs[:, control_axis] & self.zs[:, target_axis] diff --git a/cirq-core/cirq/qis/states.py b/cirq-core/cirq/qis/states.py index 46957ed6d0e..f38ec81d010 100644 --- a/cirq-core/cirq/qis/states.py +++ b/cirq-core/cirq/qis/states.py @@ -524,8 +524,7 @@ def _raise_value_error_if_ambiguous(self) -> None: 'with the corresponding qudit dimensions being at least ' f'{self.min_qudit_dimensions}.' ) - if len(self.explicit_qid_shapes) > 1: - # coverage: ignore + if len(self.explicit_qid_shapes) > 1: # pragma: no cover raise ValueError( f'Qid shape is ambiguous: Could be any one of {self.explicit_qid_shapes}.' ) diff --git a/cirq-core/cirq/sim/clifford/clifford_simulator_test.py b/cirq-core/cirq/sim/clifford/clifford_simulator_test.py index 72ff4198e7f..33232e28518 100644 --- a/cirq-core/cirq/sim/clifford/clifford_simulator_test.py +++ b/cirq-core/cirq/sim/clifford/clifford_simulator_test.py @@ -373,19 +373,19 @@ def test_clifford_circuit_2(qubits, split): x = np.random.randint(7) if x == 0: - circuit.append(cirq.X(np.random.choice(qubits))) # coverage: ignore + circuit.append(cirq.X(np.random.choice(qubits))) # pragma: no cover elif x == 1: - circuit.append(cirq.Z(np.random.choice(qubits))) # coverage: ignore + circuit.append(cirq.Z(np.random.choice(qubits))) # pragma: no cover elif x == 2: - circuit.append(cirq.Y(np.random.choice(qubits))) # coverage: ignore + circuit.append(cirq.Y(np.random.choice(qubits))) # pragma: no cover elif x == 3: - circuit.append(cirq.S(np.random.choice(qubits))) # coverage: ignore + circuit.append(cirq.S(np.random.choice(qubits))) # pragma: no cover elif x == 4: - circuit.append(cirq.H(np.random.choice(qubits))) # coverage: ignore + circuit.append(cirq.H(np.random.choice(qubits))) # pragma: no cover elif x == 5: - circuit.append(cirq.CNOT(qubits[0], qubits[1])) # coverage: ignore + circuit.append(cirq.CNOT(qubits[0], qubits[1])) # pragma: no cover elif x == 6: - circuit.append(cirq.CZ(qubits[0], qubits[1])) # coverage: ignore + circuit.append(cirq.CZ(qubits[0], qubits[1])) # pragma: no cover circuit.append(cirq.measure(qubits[0])) result = cirq.CliffordSimulator(split_untangled_states=split).run(circuit, repetitions=100) diff --git a/cirq-core/cirq/sim/clifford/stabilizer_simulation_state.py b/cirq-core/cirq/sim/clifford/stabilizer_simulation_state.py index a428e87d565..bad4bca02c0 100644 --- a/cirq-core/cirq/sim/clifford/stabilizer_simulation_state.py +++ b/cirq-core/cirq/sim/clifford/stabilizer_simulation_state.py @@ -84,7 +84,7 @@ def _swap( ): """Apply a SWAP gate""" if exponent % 1 != 0: - raise ValueError('Swap exponent must be integer') # coverage: ignore + raise ValueError('Swap exponent must be integer') # pragma: no cover self._state.apply_cx(control_axis, target_axis) self._state.apply_cx(target_axis, control_axis, exponent, global_shift) self._state.apply_cx(control_axis, target_axis) @@ -122,7 +122,7 @@ def _strat_apply_mixture(self, val: Any, qubits: Sequence['cirq.Qid']) -> bool: if mixture is None: return NotImplemented if not all(linalg.is_unitary(m) for _, m in mixture): - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover probabilities, unitaries = zip(*mixture) index = self.prng.choice(len(unitaries), p=probabilities) return self._strat_act_from_single_qubit_decompose( diff --git a/cirq-core/cirq/sim/clifford/stabilizer_state_ch_form.py b/cirq-core/cirq/sim/clifford/stabilizer_state_ch_form.py index 1c219595a3d..ef2d1a86679 100644 --- a/cirq-core/cirq/sim/clifford/stabilizer_state_ch_form.py +++ b/cirq-core/cirq/sim/clifford/stabilizer_state_ch_form.py @@ -54,7 +54,7 @@ def __init__(self, num_qubits: int, initial_state: int = 0) -> None: self.omega: complex = 1 # Apply X for every non-zero element of initial_state - for (i, val) in enumerate( + for i, val in enumerate( big_endian_int_to_digits(initial_state, digit_count=num_qubits, base=2) ): if val: @@ -295,7 +295,7 @@ def reindex(self, axes: Sequence[int]) -> 'cirq.StabilizerStateChForm': def apply_x(self, axis: int, exponent: float = 1, global_shift: float = 0): if exponent % 2 != 0: if exponent % 0.5 != 0.0: - raise ValueError('X exponent must be half integer') # coverage: ignore + raise ValueError('X exponent must be half integer') # pragma: no cover self.apply_h(axis) self.apply_z(axis, exponent) self.apply_h(axis) @@ -303,7 +303,7 @@ def apply_x(self, axis: int, exponent: float = 1, global_shift: float = 0): def apply_y(self, axis: int, exponent: float = 1, global_shift: float = 0): if exponent % 0.5 != 0.0: - raise ValueError('Y exponent must be half integer') # coverage: ignore + raise ValueError('Y exponent must be half integer') # pragma: no cover shift = _phase(exponent, global_shift) if exponent % 2 == 0: self.omega *= shift @@ -325,7 +325,7 @@ def apply_y(self, axis: int, exponent: float = 1, global_shift: float = 0): def apply_z(self, axis: int, exponent: float = 1, global_shift: float = 0): if exponent % 2 != 0: if exponent % 0.5 != 0.0: - raise ValueError('Z exponent must be half integer') # coverage: ignore + raise ValueError('Z exponent must be half integer') # pragma: no cover effective_exponent = exponent % 2 for _ in range(int(effective_exponent * 2)): # Prescription for S left multiplication. @@ -337,7 +337,7 @@ def apply_z(self, axis: int, exponent: float = 1, global_shift: float = 0): def apply_h(self, axis: int, exponent: float = 1, global_shift: float = 0): if exponent % 2 != 0: if exponent % 1 != 0: - raise ValueError('H exponent must be integer') # coverage: ignore + raise ValueError('H exponent must be integer') # pragma: no cover # Prescription for H left multiplication # Reference: https://arxiv.org/abs/1808.00128 # Equations 48, 49 and Proposition 4 @@ -357,7 +357,7 @@ def apply_cz( ): if exponent % 2 != 0: if exponent % 1 != 0: - raise ValueError('CZ exponent must be integer') # coverage: ignore + raise ValueError('CZ exponent must be integer') # pragma: no cover # Prescription for CZ left multiplication. # Reference: https://arxiv.org/abs/1808.00128 Proposition 4 end self.M[control_axis, :] ^= self.G[target_axis, :] @@ -369,7 +369,7 @@ def apply_cx( ): if exponent % 2 != 0: if exponent % 1 != 0: - raise ValueError('CX exponent must be integer') # coverage: ignore + raise ValueError('CX exponent must be integer') # pragma: no cover # Prescription for CX left multiplication. # Reference: https://arxiv.org/abs/1808.00128 Proposition 4 end self.gamma[control_axis] = ( diff --git a/cirq-core/cirq/sim/density_matrix_simulation_state.py b/cirq-core/cirq/sim/density_matrix_simulation_state.py index b3c087a2641..c7bae07cfd0 100644 --- a/cirq-core/cirq/sim/density_matrix_simulation_state.py +++ b/cirq-core/cirq/sim/density_matrix_simulation_state.py @@ -47,8 +47,7 @@ def __init__(self, density_matrix: np.ndarray, buffer: Optional[List[np.ndarray] if buffer is None: buffer = [np.empty_like(density_matrix) for _ in range(3)] self._buffer = buffer - if len(density_matrix.shape) % 2 != 0: - # coverage: ignore + if len(density_matrix.shape) % 2 != 0: # pragma: no cover raise ValueError('The dimension of target_tensor is not divisible by 2.') self._qid_shape = density_matrix.shape[: len(density_matrix.shape) // 2] @@ -86,7 +85,7 @@ def create( initial_state, len(qid_shape), qid_shape=qid_shape, dtype=dtype ).reshape(qid_shape * 2) else: - density_matrix = initial_state # coverage: ignore + density_matrix = initial_state # pragma: no cover if np.may_share_memory(density_matrix, initial_state): density_matrix = density_matrix.copy() density_matrix = density_matrix.astype(dtype, copy=False) @@ -299,7 +298,7 @@ def _act_on_fallback_( for strat in strats: result = strat(action, self, qubits) if result is False: - break # coverage: ignore + break # pragma: no cover if result is True: return True assert result is NotImplemented, str(result) diff --git a/cirq-core/cirq/sim/density_matrix_simulator_test.py b/cirq-core/cirq/sim/density_matrix_simulator_test.py index 7662471371b..119bc3f1830 100644 --- a/cirq-core/cirq/sim/density_matrix_simulator_test.py +++ b/cirq-core/cirq/sim/density_matrix_simulator_test.py @@ -139,8 +139,7 @@ def __init__(self, qubits): def qubits(self): return self._qubits - def with_qubits(self, *new_qubits): - # coverage: ignore + def with_qubits(self, *new_qubits): # pragma: no cover return BadOp(self._qubits) q0 = cirq.LineQubit(0) @@ -1050,39 +1049,32 @@ def test_density_matrix_trial_result_repr(): class XAsOp(cirq.Operation): def __init__(self, q): - # coverage: ignore - self.q = q + self.q = q # pragma: no cover @property def qubits(self): - # coverage: ignore - return (self.q,) + return (self.q,) # pragma: no cover def with_qubits(self, *new_qubits): - # coverage: ignore - return XAsOp(new_qubits[0]) + return XAsOp(new_qubits[0]) # pragma: no cover def _kraus_(self): - # coverage: ignore - return cirq.kraus(cirq.X) + return cirq.kraus(cirq.X) # pragma: no cover def test_works_on_operation(): class XAsOp(cirq.Operation): def __init__(self, q): - # coverage: ignore self.q = q @property def qubits(self): - # coverage: ignore return (self.q,) def with_qubits(self, *new_qubits): raise NotImplementedError() def _kraus_(self): - # coverage: ignore return cirq.kraus(cirq.X) s = cirq.DensityMatrixSimulator() diff --git a/cirq-core/cirq/sim/state_vector_simulation_state.py b/cirq-core/cirq/sim/state_vector_simulation_state.py index 7674e12e873..d96bf0dc6f7 100644 --- a/cirq-core/cirq/sim/state_vector_simulation_state.py +++ b/cirq-core/cirq/sim/state_vector_simulation_state.py @@ -387,7 +387,7 @@ def _act_on_fallback_( for strat in strats: result = strat(action, self, qubits) if result is False: - break # coverage: ignore + break # pragma: no cover if result is True: return True assert result is NotImplemented, str(result) diff --git a/cirq-core/cirq/testing/circuit_compare.py b/cirq-core/cirq/testing/circuit_compare.py index 74637292f7e..a5ccce6dfc0 100644 --- a/cirq-core/cirq/testing/circuit_compare.py +++ b/cirq-core/cirq/testing/circuit_compare.py @@ -218,7 +218,7 @@ def _first_differing_moment_index( for i, (m1, m2) in enumerate(itertools.zip_longest(circuit1, circuit2)): if m1 != m2: return i - return None # coverage: ignore + return None # pragma: no cover def assert_circuits_have_same_unitary_given_final_permutation( diff --git a/cirq-core/cirq/testing/circuit_compare_test.py b/cirq-core/cirq/testing/circuit_compare_test.py index 9e0e0af65df..b786516f23f 100644 --- a/cirq-core/cirq/testing/circuit_compare_test.py +++ b/cirq-core/cirq/testing/circuit_compare_test.py @@ -484,7 +484,7 @@ def _qid_shape_(self): class ConsistentOp(cirq.Operation): def with_qubits(self, *qubits): - raise NotImplementedError # coverage: ignore + raise NotImplementedError # pragma: no cover @property def qubits(self): @@ -496,47 +496,47 @@ def _num_qubits_(self): def _qid_shape_(self): return (1, 2, 3, 4) - # The 'coverage: ignore' comments in the InconsistentOp classes is needed + # The 'pragma: no cover' comments in the InconsistentOp classes is needed # because test_assert_has_consistent_qid_shape may only need to check two of # the three methods before finding an inconsistency and throwing an error. class InconsistentOp1(cirq.Operation): def with_qubits(self, *qubits): - raise NotImplementedError # coverage: ignore + raise NotImplementedError # pragma: no cover @property def qubits(self): return cirq.LineQubit.range(2) def _num_qubits_(self): - return 4 # coverage: ignore + return 4 # pragma: no cover def _qid_shape_(self): - return (1, 2, 3, 4) # coverage: ignore + return (1, 2, 3, 4) # pragma: no cover class InconsistentOp2(cirq.Operation): def with_qubits(self, *qubits): - raise NotImplementedError # coverage: ignore + raise NotImplementedError # pragma: no cover @property def qubits(self): - return cirq.LineQubit.range(4) # coverage: ignore + return cirq.LineQubit.range(4) # pragma: no cover def _num_qubits_(self): return 2 def _qid_shape_(self): - return (1, 2, 3, 4) # coverage: ignore + return (1, 2, 3, 4) # pragma: no cover class InconsistentOp3(cirq.Operation): def with_qubits(self, *qubits): - raise NotImplementedError # coverage: ignore + raise NotImplementedError # pragma: no cover @property def qubits(self): - return cirq.LineQubit.range(4) # coverage: ignore + return cirq.LineQubit.range(4) # pragma: no cover def _num_qubits_(self): - return 4 # coverage: ignore + return 4 # pragma: no cover def _qid_shape_(self): return 1, 2 diff --git a/cirq-core/cirq/testing/consistent_controlled_gate_op_test.py b/cirq-core/cirq/testing/consistent_controlled_gate_op_test.py index f815a2943c0..02d6df63267 100644 --- a/cirq-core/cirq/testing/consistent_controlled_gate_op_test.py +++ b/cirq-core/cirq/testing/consistent_controlled_gate_op_test.py @@ -23,8 +23,7 @@ class GoodGate(cirq.EigenGate, cirq.testing.SingleQubitGate): - def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: - # coverage: ignore + def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: # pragma: no cover return [(0, np.diag([1, 0])), (1, np.diag([0, 1]))] @@ -41,7 +40,6 @@ def controlled_by( class BadGate(cirq.EigenGate, cirq.testing.SingleQubitGate): def _eigen_components(self) -> List[Tuple[float, np.ndarray]]: - # coverage: ignore return [(0, np.diag([1, 0])), (1, np.diag([0, 1]))] def on(self, *qubits: 'cirq.Qid') -> 'cirq.Operation': diff --git a/cirq-core/cirq/testing/consistent_decomposition.py b/cirq-core/cirq/testing/consistent_decomposition.py index 2572a956d2f..fcde456bb35 100644 --- a/cirq-core/cirq/testing/consistent_decomposition.py +++ b/cirq-core/cirq/testing/consistent_decomposition.py @@ -54,7 +54,6 @@ def assert_decompose_is_consistent_with_unitary(val: Any, ignoring_global_phase: if ignoring_global_phase: lin_alg_utils.assert_allclose_up_to_global_phase(actual, expected, atol=1e-8) else: - # coverage: ignore np.testing.assert_allclose(actual, expected, atol=1e-8) diff --git a/cirq-core/cirq/testing/consistent_protocols_test.py b/cirq-core/cirq/testing/consistent_protocols_test.py index 123e6a6b010..2b1c4572967 100644 --- a/cirq-core/cirq/testing/consistent_protocols_test.py +++ b/cirq-core/cirq/testing/consistent_protocols_test.py @@ -87,8 +87,7 @@ def _phase_by_(self, phase_turns, qubit_index): def __pow__(self, exponent: Union[float, sympy.Expr]) -> 'GoodGate': new_exponent = cirq.mul(self.exponent, exponent, NotImplemented) if new_exponent is NotImplemented: - # coverage: ignore - return NotImplemented + return NotImplemented # pragma: no cover return GoodGate(phase_exponent=self.phase_exponent, exponent=new_exponent) def __repr__(self): @@ -114,8 +113,7 @@ def _identity_tuple(self): def __eq__(self, other): if not isinstance(other, type(self)): - # coverage: ignore - return NotImplemented + return NotImplemented # pragma: no cover return self._identity_tuple() == other._identity_tuple() @@ -132,8 +130,7 @@ def _parameter_names_(self) -> AbstractSet[str]: class BadGateApplyUnitaryToTensor(GoodGate): def _apply_unitary_(self, args: cirq.ApplyUnitaryArgs) -> Union[np.ndarray, NotImplementedType]: if self.exponent != 1 or cirq.is_parameterized(self): - # coverage: ignore - return NotImplemented + return NotImplemented # pragma: no cover zero = cirq.slice_for_qubits_equal_to(args.axes, 0) one = cirq.slice_for_qubits_equal_to(args.axes, 1) @@ -154,8 +151,7 @@ def _decompose_(self, qubits: Sequence[cirq.Qid]) -> cirq.OP_TREE: z = cirq.Z(q) ** self.phase_exponent x = cirq.X(q) ** (2 * self.exponent) if cirq.is_parameterized(z): - # coverage: ignore - return NotImplemented + return NotImplemented # pragma: no cover return z**-1, x, z @@ -176,8 +172,7 @@ class BadGateRepr(GoodGate): def __repr__(self): args = [f'phase_exponent={2 * self.phase_exponent!r}'] if self.exponent != 1: - # coverage: ignore - args.append(f'exponent={proper_repr(self.exponent)}') + args.append(f'exponent={proper_repr(self.exponent)}') # pragma: no cover return f"BadGateRepr({', '.join(args)})" diff --git a/cirq-core/cirq/testing/consistent_qasm.py b/cirq-core/cirq/testing/consistent_qasm.py index a6a0608316d..e61095e9053 100644 --- a/cirq-core/cirq/testing/consistent_qasm.py +++ b/cirq-core/cirq/testing/consistent_qasm.py @@ -27,8 +27,7 @@ def assert_qasm_is_consistent_with_unitary(val: Any): # Only test if qiskit is installed. try: import qiskit - except ImportError: - # coverage: ignore + except ImportError: # pragma: no cover warnings.warn( "Skipped assert_qasm_is_consistent_with_unitary because " "qiskit isn't installed to verify against." @@ -101,8 +100,7 @@ def assert_qasm_is_consistent_with_unitary(val: Any): ) -def assert_qiskit_parsed_qasm_consistent_with_unitary(qasm, unitary): - # coverage: ignore +def assert_qiskit_parsed_qasm_consistent_with_unitary(qasm, unitary): # pragma: no cover try: # We don't want to require qiskit as a dependency but # if Qiskit is installed, test QASM output against it. diff --git a/cirq-core/cirq/testing/consistent_qasm_test.py b/cirq-core/cirq/testing/consistent_qasm_test.py index a308e64222b..a86a6d7798b 100644 --- a/cirq-core/cirq/testing/consistent_qasm_test.py +++ b/cirq-core/cirq/testing/consistent_qasm_test.py @@ -54,8 +54,7 @@ def _qasm_(self, args: cirq.QasmArgs, qubits: Tuple[cirq.Qid, ...]): def test_assert_qasm_is_consistent_with_unitary(): try: import qiskit as _ - except ImportError: - # coverage: ignore + except ImportError: # pragma: no cover warnings.warn( "Skipped test_assert_qasm_is_consistent_with_unitary " "because qiskit isn't installed to verify against." diff --git a/cirq-core/cirq/testing/consistent_specified_has_unitary_test.py b/cirq-core/cirq/testing/consistent_specified_has_unitary_test.py index 241967b14db..6295c27debc 100644 --- a/cirq-core/cirq/testing/consistent_specified_has_unitary_test.py +++ b/cirq-core/cirq/testing/consistent_specified_has_unitary_test.py @@ -32,12 +32,10 @@ def test_assert_specifies_has_unitary_if_unitary_from_apply(): class Bad(cirq.Operation): @property def qubits(self): - # coverage: ignore return () def with_qubits(self, *new_qubits): - # coverage: ignore - return self + return self # pragma: no cover def _apply_unitary_(self, args): return args.target_tensor diff --git a/cirq-core/cirq/testing/equals_tester.py b/cirq-core/cirq/testing/equals_tester.py index 80e025f0b2b..9798519909d 100644 --- a/cirq-core/cirq/testing/equals_tester.py +++ b/cirq-core/cirq/testing/equals_tester.py @@ -157,7 +157,7 @@ def __init__(self, other: object) -> None: def __eq__(self, other: object) -> bool: if other is not self.other: - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover return True diff --git a/cirq-core/cirq/testing/equals_tester_test.py b/cirq-core/cirq/testing/equals_tester_test.py index 7aed15e3948..59127f3b50f 100644 --- a/cirq-core/cirq/testing/equals_tester_test.py +++ b/cirq-core/cirq/testing/equals_tester_test.py @@ -169,16 +169,16 @@ def __init__(self): def __eq__(self, other): if not isinstance(other, type(self)): - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover return self.x == other.x def __ne__(self, other): if not isinstance(other, type(self)): - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover return self.x == other.x def __hash__(self): - return hash(self.x) # coverage: ignore + return hash(self.x) # pragma: no cover with pytest.raises(AssertionError, match='inconsistent'): eq.make_equality_group(InconsistentNeImplementation) @@ -278,7 +278,7 @@ def __eq__(self, other): if isinstance(other, (FirstClass, SecondClass)): return self.val == other.val # Ignore coverage, this is just for illustrative purposes. - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover # But we see that this does not work because it fails commutativity of == assert SecondClass("a") == FirstClass("a") @@ -306,7 +306,7 @@ def __eq__(self, other): if isinstance(other, (ThirdClass, FourthClass)): return self.val == other.val # Ignore coverage, this is just for illustrative purposes. - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover # We see this is fixed: assert ThirdClass("a") == FourthClass("a") diff --git a/cirq-core/cirq/testing/equivalent_repr_eval_test.py b/cirq-core/cirq/testing/equivalent_repr_eval_test.py index de087b6196d..7683a072f41 100644 --- a/cirq-core/cirq/testing/equivalent_repr_eval_test.py +++ b/cirq-core/cirq/testing/equivalent_repr_eval_test.py @@ -30,9 +30,7 @@ def test_external(): def test_custom_class_repr(): - class CustomRepr: - # coverage: ignore - + class CustomRepr: # pragma: no cover setup_code = """class CustomRepr: def __init__(self, eq_val): self.eq_val = eq_val diff --git a/cirq-core/cirq/testing/order_tester_test.py b/cirq-core/cirq/testing/order_tester_test.py index c5dd90d6c81..afeb425661d 100644 --- a/cirq-core/cirq/testing/order_tester_test.py +++ b/cirq-core/cirq/testing/order_tester_test.py @@ -89,9 +89,7 @@ def test_add_ordering_group_incorrect(): def test_propagates_internal_errors(): - class UnorderableClass: - # coverage: ignore - + class UnorderableClass: # pragma: no cover def __eq__(self, other): return NotImplemented diff --git a/cirq-core/cirq/testing/random_circuit_test.py b/cirq-core/cirq/testing/random_circuit_test.py index 9203ef0d0d8..3af5136f02d 100644 --- a/cirq-core/cirq/testing/random_circuit_test.py +++ b/cirq-core/cirq/testing/random_circuit_test.py @@ -60,8 +60,7 @@ def _cases_for_random_circuit(): # number of qubits greater that the number of qubits for the # circuit. In this case, try again. if all(n > n_qubits for n in gate_domain.values()): - # coverage: ignore - continue + continue # pragma: no cover else: gate_domain = None pass_qubits = random.choice((True, False)) @@ -107,7 +106,6 @@ def test_random_circuit_reproducible_with_seed(seed): def test_random_circuit_not_expected_number_of_qubits(): - circuit = cirq.testing.random_circuit( qubits=3, n_moments=1, op_density=1.0, gate_domain={cirq.CNOT: 2} ) diff --git a/cirq-core/cirq/transformers/analytical_decompositions/three_qubit_decomposition.py b/cirq-core/cirq/transformers/analytical_decompositions/three_qubit_decomposition.py index 09ecedab26c..0990e4dba24 100644 --- a/cirq-core/cirq/transformers/analytical_decompositions/three_qubit_decomposition.py +++ b/cirq-core/cirq/transformers/analytical_decompositions/three_qubit_decomposition.py @@ -56,8 +56,7 @@ def three_qubit_matrix_to_operations( try: from scipy.linalg import cossin - except ImportError: # coverage: ignore - # coverage: ignore + except ImportError: # pragma: no cover raise ImportError( "cirq.three_qubit_unitary_to_operations requires " "SciPy 1.5.0+, as it uses the cossin function. Please" diff --git a/cirq-core/cirq/transformers/analytical_decompositions/three_qubit_decomposition_test.py b/cirq-core/cirq/transformers/analytical_decompositions/three_qubit_decomposition_test.py index 274203c5831..917f2c2765b 100644 --- a/cirq-core/cirq/transformers/analytical_decompositions/three_qubit_decomposition_test.py +++ b/cirq-core/cirq/transformers/analytical_decompositions/three_qubit_decomposition_test.py @@ -30,15 +30,13 @@ def _skip_if_scipy(*, version_is_greater_than_1_5_0: bool) -> Callable[[Callable], Callable]: - def decorator(func): + def decorator(func): # pragma: no cover try: # pylint: disable=unused-import from scipy.linalg import cossin - # coverage: ignore return None if version_is_greater_than_1_5_0 else func except ImportError: - # coverage: ignore return func if version_is_greater_than_1_5_0 else None return decorator @@ -84,8 +82,7 @@ def test_three_qubit_matrix_to_operations_errors(): # environment like that, we'll need to ignore the coverage somehow conditionally on # the scipy version. @_skip_if_scipy(version_is_greater_than_1_5_0=True) -# coverage: ignore -def test_three_qubit_matrix_to_operations_scipy_error(): +def test_three_qubit_matrix_to_operations_scipy_error(): # pragma: no cover a, b, c = cirq.LineQubit.range(3) with pytest.raises(ImportError, match="three_qubit.*1.5.0+"): cirq.three_qubit_matrix_to_operations(a, b, c, np.eye(8)) diff --git a/cirq-core/cirq/transformers/heuristic_decompositions/gate_tabulation_math_utils.py b/cirq-core/cirq/transformers/heuristic_decompositions/gate_tabulation_math_utils.py index 1c6e1f310a9..31d46f7aaaf 100644 --- a/cirq-core/cirq/transformers/heuristic_decompositions/gate_tabulation_math_utils.py +++ b/cirq-core/cirq/transformers/heuristic_decompositions/gate_tabulation_math_utils.py @@ -174,7 +174,7 @@ def kak_vector_infidelity( # Ensure we consider equivalent vectors for only the smallest input. if k_vec_a.size < k_vec_b.size: - k_vec_a, k_vec_b = k_vec_b, k_vec_a # coverage: ignore + k_vec_a, k_vec_b = k_vec_b, k_vec_a # pragma: no cover k_vec_a = k_vec_a[..., np.newaxis, :] # (...,1,3) k_vec_b = _kak_equivalent_vectors(k_vec_b) # (...,192,3) diff --git a/cirq-core/cirq/transformers/stratify.py b/cirq-core/cirq/transformers/stratify.py index 04e130c4a78..228642aa8bd 100644 --- a/cirq-core/cirq/transformers/stratify.py +++ b/cirq-core/cirq/transformers/stratify.py @@ -130,7 +130,6 @@ def _stratify_circuit( ignored_ops = [] op_time_indices = {} for op in moment: - # Identify the earliest moment that can accommodate this op. min_time_index_for_op = circuits.circuit.get_earliest_accommodating_moment_index( op, qubit_time_index, measurement_time_index, control_time_index @@ -224,7 +223,7 @@ def _category_to_classifier(category) -> Classifier: def _dummy_classifier(op: 'cirq.Operation') -> bool: """Dummy classifier, used to "complete" a collection of classifiers and make it exhaustive.""" - return False # coverage: ignore + return False # pragma: no cover def _get_op_class(op: 'cirq.Operation', classifiers: Sequence[Classifier]) -> int: diff --git a/cirq-core/cirq/transformers/target_gatesets/cz_gateset_test.py b/cirq-core/cirq/transformers/target_gatesets/cz_gateset_test.py index 00f31414d2a..5be583bf351 100644 --- a/cirq-core/cirq/transformers/target_gatesets/cz_gateset_test.py +++ b/cirq-core/cirq/transformers/target_gatesets/cz_gateset_test.py @@ -231,8 +231,7 @@ def test_not_decompose_partial_czs(): def test_avoids_decompose_when_matrix_available(): - class OtherXX(cirq.testing.TwoQubitGate): - # coverage: ignore + class OtherXX(cirq.testing.TwoQubitGate): # pragma: no cover def _has_unitary_(self) -> bool: return True @@ -243,8 +242,7 @@ def _unitary_(self) -> np.ndarray: def _decompose_(self, qubits): assert False - class OtherOtherXX(cirq.testing.TwoQubitGate): - # coverage: ignore + class OtherOtherXX(cirq.testing.TwoQubitGate): # pragma: no cover def _has_unitary_(self) -> bool: return True diff --git a/cirq-core/cirq/value/abc_alt_test.py b/cirq-core/cirq/value/abc_alt_test.py index bbbf53af73c..df8ade164d0 100644 --- a/cirq-core/cirq/value/abc_alt_test.py +++ b/cirq-core/cirq/value/abc_alt_test.py @@ -140,7 +140,7 @@ def test_classcell_in_namespace(): class _(metaclass=ABCMetaImplementAnyOneOf): def other_method(self): # Triggers __classcell__ to be added to the class namespace - super() # coverage: ignore + super() # pragma: no cover def test_two_alternatives(): @@ -170,17 +170,17 @@ def alt1(self) -> str: return 'alt1' def alt2(self) -> NoReturn: - raise RuntimeError # coverage: ignore + raise RuntimeError # pragma: no cover class TwoAlternativesOverride(TwoAlternatives): def my_method(self, arg, kw=99) -> str: return 'override' def alt1(self) -> NoReturn: - raise RuntimeError # coverage: ignore + raise RuntimeError # pragma: no cover def alt2(self) -> NoReturn: - raise RuntimeError # coverage: ignore + raise RuntimeError # pragma: no cover class TwoAlternativesForceSecond(TwoAlternatives): def _do_alt1_with_my_method(self): diff --git a/cirq-core/cirq/value/measurement_key_test.py b/cirq-core/cirq/value/measurement_key_test.py index 75ccbf31eab..b834832cbc1 100644 --- a/cirq-core/cirq/value/measurement_key_test.py +++ b/cirq-core/cirq/value/measurement_key_test.py @@ -43,7 +43,7 @@ def __init__(self, some_str): self.some_str = some_str def __str__(self): - return self.some_str # coverage: ignore + return self.some_str # pragma: no cover mkey = cirq.MeasurementKey('key') assert mkey == 'key' diff --git a/cirq-core/cirq/value/product_state.py b/cirq-core/cirq/value/product_state.py index e7a76e2c1b7..84647fcee7c 100644 --- a/cirq-core/cirq/value/product_state.py +++ b/cirq-core/cirq/value/product_state.py @@ -61,8 +61,7 @@ class ProductState: def __init__(self, states=None): if states is None: - # coverage: ignore - states = dict() + states = dict() # pragma: no cover object.__setattr__(self, 'states', states) @@ -200,8 +199,7 @@ def state_vector(self) -> np.ndarray: return np.array([1, 1]) / np.sqrt(2) elif self.eigenvalue == -1: return np.array([1, -1]) / np.sqrt(2) - # coverage: ignore - raise ValueError(f"Bad eigenvalue: {self.eigenvalue}") + raise ValueError(f"Bad eigenvalue: {self.eigenvalue}") # pragma: no cover def stabilized_by(self) -> Tuple[int, 'cirq.Pauli']: # Prevent circular import from `value.value_equality` @@ -218,8 +216,7 @@ def state_vector(self) -> np.ndarray: return np.array([1, 1j]) / np.sqrt(2) elif self.eigenvalue == -1: return np.array([1, -1j]) / np.sqrt(2) - # coverage: ignore - raise ValueError(f"Bad eigenvalue: {self.eigenvalue}") + raise ValueError(f"Bad eigenvalue: {self.eigenvalue}") # pragma: no cover def stabilized_by(self) -> Tuple[int, 'cirq.Pauli']: from cirq import ops @@ -235,8 +232,7 @@ def state_vector(self) -> np.ndarray: return np.array([1, 0]) elif self.eigenvalue == -1: return np.array([0, 1]) - # coverage: ignore - raise ValueError(f"Bad eigenvalue: {self.eigenvalue}") + raise ValueError(f"Bad eigenvalue: {self.eigenvalue}") # pragma: no cover def stabilized_by(self) -> Tuple[int, 'cirq.Pauli']: from cirq import ops diff --git a/cirq-core/cirq/value/value_equality_attr.py b/cirq-core/cirq/value/value_equality_attr.py index c36fc1355c8..31d570430a6 100644 --- a/cirq-core/cirq/value/value_equality_attr.py +++ b/cirq-core/cirq/value/value_equality_attr.py @@ -50,8 +50,7 @@ def _value_equality_approximate_values_(self) -> Any: Returns: Any type supported by `cirq.approx_eq()`. """ - # coverage: ignore - return self._value_equality_values_() + return self._value_equality_values_() # pragma: no cover def _value_equality_values_cls_(self) -> Any: """Automatically implemented by the `cirq.value_equality` decorator. diff --git a/cirq-ft/cirq_ft/algos/and_gate.py b/cirq-ft/cirq_ft/algos/and_gate.py index aab45a978e7..973528386dc 100644 --- a/cirq-ft/cirq_ft/algos/and_gate.py +++ b/cirq-ft/cirq_ft/algos/and_gate.py @@ -66,7 +66,7 @@ def __pow__(self, power: int) -> "And": return self if power == -1: return And(self.cv, adjoint=self.adjoint ^ True) - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover def __str__(self) -> str: suffix = "" if self.cv == (1,) * len(self.cv) else str(self.cv) diff --git a/cirq-ft/cirq_ft/algos/arithmetic_gates.py b/cirq-ft/cirq_ft/algos/arithmetic_gates.py index d477c598e77..b75383015e3 100644 --- a/cirq-ft/cirq_ft/algos/arithmetic_gates.py +++ b/cirq-ft/cirq_ft/algos/arithmetic_gates.py @@ -47,7 +47,7 @@ def _circuit_diagram_info_(self, _) -> cirq.CircuitDiagramInfo: def __pow__(self, power: int): if power in [1, -1]: return self - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover def __repr__(self) -> str: return f'cirq_ft.LessThanGate({self.bitsize}, {self.less_than_val})' @@ -200,7 +200,7 @@ def __pow__(self, power: int) -> cirq.Gate: return self if power == -1: return BiQubitsMixer(adjoint=not self.adjoint) - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover def _t_complexity_(self) -> infra.TComplexity: if self.adjoint: @@ -302,7 +302,7 @@ def _circuit_diagram_info_(self, _) -> cirq.CircuitDiagramInfo: def __pow__(self, power: int): if power in [1, -1]: return self - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover def __repr__(self) -> str: return f'cirq_ft.LessThanEqualGate({self.x_bitsize}, {self.y_bitsize})' @@ -506,7 +506,7 @@ def __repr__(self) -> str: def __pow__(self, power: int): if power in [1, -1]: return self - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover @attr.frozen diff --git a/cirq-ft/cirq_ft/algos/mean_estimation/arctan.py b/cirq-ft/cirq_ft/algos/mean_estimation/arctan.py index 5145737ce72..f125a215605 100644 --- a/cirq-ft/cirq_ft/algos/mean_estimation/arctan.py +++ b/cirq-ft/cirq_ft/algos/mean_estimation/arctan.py @@ -56,4 +56,4 @@ def _t_complexity_(self) -> infra.TComplexity: def __pow__(self, power) -> 'ArcTan': if power in [+1, -1]: return self - raise NotImplementedError("__pow__ is only implemented for +1/-1.") # coverage: ignore + raise NotImplementedError("__pow__ is only implemented for +1/-1.") # pragma: no cover diff --git a/cirq-ft/cirq_ft/algos/mean_estimation/mean_estimation_operator_test.py b/cirq-ft/cirq_ft/algos/mean_estimation/mean_estimation_operator_test.py index 5460c8ad194..f9f7c359165 100644 --- a/cirq-ft/cirq_ft/algos/mean_estimation/mean_estimation_operator_test.py +++ b/cirq-ft/cirq_ft/algos/mean_estimation/mean_estimation_operator_test.py @@ -76,9 +76,9 @@ def decompose_from_registers( # type:ignore[override] for y0, y1, tq in zip(y0_bin, y1_bin, t): if y0: - yield cirq.X(tq).controlled_by( # coverage: ignore - *q, control_values=[0] * self.selection_bitsize # coverage: ignore - ) # coverage: ignore + yield cirq.X(tq).controlled_by( # pragma: no cover + *q, control_values=[0] * self.selection_bitsize # pragma: no cover + ) # pragma: no cover if y1: yield cirq.X(tq).controlled_by(*q, control_values=[1] * self.selection_bitsize) @@ -185,7 +185,7 @@ def decompose_from_registers( # type:ignore[override] def __pow__(self, power): if power in [+1, -1]: return self - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover @frozen diff --git a/cirq-ft/cirq_ft/algos/qrom.py b/cirq-ft/cirq_ft/algos/qrom.py index e07ffe29b86..85c3eca1976 100644 --- a/cirq-ft/cirq_ft/algos/qrom.py +++ b/cirq-ft/cirq_ft/algos/qrom.py @@ -169,7 +169,7 @@ def _circuit_diagram_info_(self, _) -> cirq.CircuitDiagramInfo: def __pow__(self, power: int): if power in [1, -1]: return self - return NotImplemented # coverage: ignore + return NotImplemented # pragma: no cover def _value_equality_values_(self): return (self.selection_registers, self.target_registers, self.control_registers) diff --git a/cirq-ft/cirq_ft/infra/qubit_management_transformers.py b/cirq-ft/cirq_ft/infra/qubit_management_transformers.py index 390ee1dc1e1..b092545de1d 100644 --- a/cirq-ft/cirq_ft/infra/qubit_management_transformers.py +++ b/cirq-ft/cirq_ft/infra/qubit_management_transformers.py @@ -140,8 +140,8 @@ def map_func(op: cirq.Operation, idx: int) -> cirq.OP_TREE: assert st < idx and q in allocated_map # This line is actually covered by # `test_map_clean_and_borrowable_qubits_deallocates_only_once` but pytest-cov seems - # to not recognize it and hence the coverage: ignore. - continue # coverage: ignore + # to not recognize it and hence the pragma: no cover. + continue # pragma: no cover # This is the first time we are seeing this temporary qubit and need to find a mapping. if isinstance(q, cirq.ops.CleanQubit): diff --git a/cirq-ft/cirq_ft/infra/t_complexity_protocol_test.py b/cirq-ft/cirq_ft/infra/t_complexity_protocol_test.py index 9b2fb789141..851e5907119 100644 --- a/cirq-ft/cirq_ft/infra/t_complexity_protocol_test.py +++ b/cirq-ft/cirq_ft/infra/t_complexity_protocol_test.py @@ -186,7 +186,7 @@ def _t_complexity_(self) -> cirq_ft.TComplexity: @property def qubits(self): - return [cirq.LineQubit(3)] # coverage: ignore + return [cirq.LineQubit(3)] # pragma: no cover def with_qubits(self, _): ... diff --git a/cirq-google/cirq_google/_version.py b/cirq-google/cirq_google/_version.py index dae8a271d9d..2928a84c448 100644 --- a/cirq-google/cirq_google/_version.py +++ b/cirq-google/cirq_google/_version.py @@ -17,8 +17,7 @@ import sys -if sys.version_info < (3, 9, 0): - # coverage: ignore +if sys.version_info < (3, 9, 0): # pragma: no cover raise SystemError( "You installed the latest version of cirq but aren't on python 3.9+.\n" 'To fix this error, you need to either:\n' diff --git a/cirq-google/cirq_google/api/v1/programs.py b/cirq-google/cirq_google/api/v1/programs.py index c9448f1e4a3..be0b149d89f 100644 --- a/cirq-google/cirq_google/api/v1/programs.py +++ b/cirq-google/cirq_google/api/v1/programs.py @@ -41,40 +41,35 @@ def gate_to_proto( if isinstance(gate, cirq.XPowGate): if len(qubits) != 1: - # coverage: ignore - raise ValueError('Wrong number of qubits.') + raise ValueError('Wrong number of qubits.') # pragma: no cover return operations_pb2.Operation( incremental_delay_picoseconds=delay, exp_w=_x_to_proto(gate, qubits[0]) ) if isinstance(gate, cirq.YPowGate): if len(qubits) != 1: - # coverage: ignore - raise ValueError('Wrong number of qubits.') + raise ValueError('Wrong number of qubits.') # pragma: no cover return operations_pb2.Operation( incremental_delay_picoseconds=delay, exp_w=_y_to_proto(gate, qubits[0]) ) if isinstance(gate, cirq.PhasedXPowGate): if len(qubits) != 1: - # coverage: ignore - raise ValueError('Wrong number of qubits.') + raise ValueError('Wrong number of qubits.') # pragma: no cover return operations_pb2.Operation( incremental_delay_picoseconds=delay, exp_w=_phased_x_to_proto(gate, qubits[0]) ) if isinstance(gate, cirq.ZPowGate): if len(qubits) != 1: - # coverage: ignore - raise ValueError('Wrong number of qubits.') + raise ValueError('Wrong number of qubits.') # pragma: no cover return operations_pb2.Operation( incremental_delay_picoseconds=delay, exp_z=_z_to_proto(gate, qubits[0]) ) if isinstance(gate, cirq.CZPowGate): if len(qubits) != 2: - # coverage: ignore - raise ValueError('Wrong number of qubits.') + raise ValueError('Wrong number of qubits.') # pragma: no cover return operations_pb2.Operation( incremental_delay_picoseconds=delay, exp_11=_cz_to_proto(gate, *qubits) ) diff --git a/cirq-google/cirq_google/api/v1/programs_test.py b/cirq-google/cirq_google/api/v1/programs_test.py index e02834387ee..57917d3fe8d 100644 --- a/cirq-google/cirq_google/api/v1/programs_test.py +++ b/cirq-google/cirq_google/api/v1/programs_test.py @@ -56,8 +56,7 @@ def make_bytes(s: str) -> bytes: pass elif c == '1': byte |= 1 << idx - else: - # coverage: ignore + else: # pragma: no cover continue idx += 1 if idx == 8: diff --git a/cirq-google/cirq_google/api/v2/sweeps.py b/cirq-google/cirq_google/api/v2/sweeps.py index af1195523a8..0eb33e63bcf 100644 --- a/cirq-google/cirq_google/api/v2/sweeps.py +++ b/cirq-google/cirq_google/api/v2/sweeps.py @@ -122,8 +122,7 @@ def sweep_from_proto(msg: run_context_pb2.Sweep) -> cirq.Sweep: raise ValueError(f'single sweep type not set: {msg}') - # coverage: ignore - raise ValueError(f'sweep type not set: {msg}') + raise ValueError(f'sweep type not set: {msg}') # pragma: no cover def run_context_to_proto( diff --git a/cirq-google/cirq_google/api/v2/sweeps_test.py b/cirq-google/cirq_google/api/v2/sweeps_test.py index 97569da9ea9..f4cc144b40b 100644 --- a/cirq-google/cirq_google/api/v2/sweeps_test.py +++ b/cirq-google/cirq_google/api/v2/sweeps_test.py @@ -24,16 +24,13 @@ class UnknownSweep(sweeps.SingleSweep): - def _tuple(self): - # coverage: ignore + def _tuple(self): # pragma: no cover return self.key, tuple(range(10)) def __len__(self) -> int: - # coverage: ignore return 10 def _values(self) -> Iterator[float]: - # coverage: ignore return iter(range(10)) diff --git a/cirq-google/cirq_google/calibration/phased_fsim.py b/cirq-google/cirq_google/calibration/phased_fsim.py index fbad49611cf..fbef6271e0f 100644 --- a/cirq-google/cirq_google/calibration/phased_fsim.py +++ b/cirq-google/cirq_google/calibration/phased_fsim.py @@ -1048,7 +1048,7 @@ def with_zeta_chi_gamma_compensated( engine_gate = self.engine_gate else: if cirq.num_qubits(engine_gate) != 2: - raise ValueError('Engine gate must be a two-qubit gate') # coverage: ignore + raise ValueError('Engine gate must be a two-qubit gate') # pragma: no cover a, b = qubits diff --git a/cirq-google/cirq_google/calibration/workflow.py b/cirq-google/cirq_google/calibration/workflow.py index 864dedcaefa..37bf3456c09 100644 --- a/cirq-google/cirq_google/calibration/workflow.py +++ b/cirq-google/cirq_google/calibration/workflow.py @@ -820,7 +820,7 @@ def run_calibrations( if isinstance(sampler, AbstractEngine): if processor_id is None: - raise ValueError('processor_id must be provided.') # coverage: ignore + raise ValueError('processor_id must be provided.') # pragma: no cover processor: Optional[AbstractProcessor] = sampler.get_processor(processor_id=processor_id) elif isinstance(sampler, ProcessorSampler): processor = sampler.processor @@ -828,7 +828,6 @@ def run_calibrations( processor = None if processor is not None: - if calibration_request_type == LocalXEBPhasedFSimCalibrationRequest: engine_sampler = processor.get_sampler() return _run_local_calibrations_via_sampler(calibrations, engine_sampler) diff --git a/cirq-google/cirq_google/devices/grid_device.py b/cirq-google/cirq_google/devices/grid_device.py index 7dea6a4649e..702e8698a07 100644 --- a/cirq-google/cirq_google/devices/grid_device.py +++ b/cirq-google/cirq_google/devices/grid_device.py @@ -249,8 +249,7 @@ def _deserialize_gateset_and_gate_durations( gate_name = gate_spec.WhichOneof('gate') gate_rep = next((gr for gr in _GATES if gr.gate_spec_name == gate_name), None) - if gate_rep is None: - # coverage: ignore + if gate_rep is None: # pragma: no cover warnings.warn( f"The DeviceSpecification contains the gate '{gate_name}' which is not recognized" " by Cirq and will be ignored. This may be due to an out-of-date Cirq version.", @@ -460,9 +459,9 @@ def from_proto(cls, proto: v2.device_pb2.DeviceSpecification) -> 'GridDevice': all_qubits=all_qubits, compilation_target_gatesets=_build_compilation_target_gatesets(gateset), ) - except ValueError as ve: # coverage: ignore + except ValueError as ve: # pragma: no cover # Spec errors should have been caught in validation above. - raise ValueError("DeviceSpecification is invalid.") from ve # coverage: ignore + raise ValueError("DeviceSpecification is invalid.") from ve # pragma: no cover return GridDevice(metadata) diff --git a/cirq-google/cirq_google/engine/abstract_local_job_test.py b/cirq-google/cirq_google/engine/abstract_local_job_test.py index 1d6d92ae735..df1f6e798d3 100644 --- a/cirq-google/cirq_google/engine/abstract_local_job_test.py +++ b/cirq-google/cirq_google/engine/abstract_local_job_test.py @@ -33,7 +33,7 @@ def execution_status(self) -> quantum.ExecutionStatus.State: return self._status def failure(self) -> Optional[Tuple[str, str]]: - return ('failed', 'failure code') # coverage: ignore + return ('failed', 'failure code') # pragma: no cover def cancel(self) -> None: pass @@ -42,13 +42,13 @@ def delete(self) -> None: pass async def batched_results_async(self) -> Sequence[Sequence[EngineResult]]: - return [] # coverage: ignore + return [] # pragma: no cover async def results_async(self) -> Sequence[EngineResult]: - return [] # coverage: ignore + return [] # pragma: no cover async def calibration_results_async(self) -> Sequence[CalibrationResult]: - return [] # coverage: ignore + return [] # pragma: no cover def test_description_and_labels(): diff --git a/cirq-google/cirq_google/engine/engine_job.py b/cirq-google/cirq_google/engine/engine_job.py index 88b26f3e0b8..5fbfca657f2 100644 --- a/cirq-google/cirq_google/engine/engine_job.py +++ b/cirq-google/cirq_google/engine/engine_job.py @@ -286,7 +286,7 @@ async def results_async(self) -> Sequence[EngineResult]: or result_type == 'cirq.api.google.v1.Result' ): v1_parsed_result = v1.program_pb2.Result.FromString(result.value) - self._results = self._get_job_results_v1(v1_parsed_result) # coverage: ignore + self._results = self._get_job_results_v1(v1_parsed_result) # pragma: no cover elif ( result_type == 'cirq.google.api.v2.Result' or result_type == 'cirq.api.google.v2.Result' @@ -341,7 +341,6 @@ async def calibration_results_async(self) -> Sequence[CalibrationResult]: return self._calibration_results def _get_job_results_v1(self, result: v1.program_pb2.Result) -> Sequence[EngineResult]: - # coverage: ignore job_id = self.id() job_finished = self.update_time() diff --git a/cirq-google/cirq_google/engine/engine_processor_test.py b/cirq-google/cirq_google/engine/engine_processor_test.py index d600cc291a3..61ac367704f 100644 --- a/cirq-google/cirq_google/engine/engine_processor_test.py +++ b/cirq-google/cirq_google/engine/engine_processor_test.py @@ -701,8 +701,7 @@ def wrapper(*args, **kwargs): if orig_exist: # mypy can't resolve that orig_exist ensures that orig_value # of type Optional[str] can't be None - # coverage: ignore - os.environ[ALLOW_DEPRECATION_IN_TEST] = orig_value + os.environ[ALLOW_DEPRECATION_IN_TEST] = orig_value # pragma: no cover else: del os.environ[ALLOW_DEPRECATION_IN_TEST] diff --git a/cirq-google/cirq_google/engine/engine_result_test.py b/cirq-google/cirq_google/engine/engine_result_test.py index b836b8fa588..bfb92b324d0 100644 --- a/cirq-google/cirq_google/engine/engine_result_test.py +++ b/cirq-google/cirq_google/engine/engine_result_test.py @@ -94,8 +94,7 @@ def records(self) -> Mapping[str, np.ndarray]: return {k: v[:, np.newaxis, :] for k, v in self.measurements.items()} @property - def data(self) -> pd.DataFrame: - # coverage: ignore + def data(self) -> pd.DataFrame: # pragma: no cover return cirq.Result.dataframe_from_measurements(self.measurements) diff --git a/cirq-google/cirq_google/engine/stream_manager.py b/cirq-google/cirq_google/engine/stream_manager.py index a0bd9542ce9..b5bb5696eda 100644 --- a/cirq-google/cirq_google/engine/stream_manager.py +++ b/cirq-google/cirq_google/engine/stream_manager.py @@ -230,7 +230,7 @@ async def _manage_execution( # Ignoring coverage since this is rarely triggered. # TODO(#5996) Consider awaiting for the queue to become available, once it is changed # to be local to the asyncio thread. - await asyncio.sleep(1) # coverage: ignore + await asyncio.sleep(1) # pragma: no cover current_request = create_program_and_job_request while True: @@ -274,8 +274,7 @@ async def _manage_execution( _to_create_job_request(create_program_and_job_request), ) continue - else: - # coverage: ignore + else: # pragma: no cover raise ValueError( 'The Quantum Engine response type is not recognized by this client. ' 'This may be due to an outdated version of cirq-google' diff --git a/cirq-google/cirq_google/engine/virtual_engine_factory.py b/cirq-google/cirq_google/engine/virtual_engine_factory.py index fcb1a168c76..451db1e00fe 100644 --- a/cirq-google/cirq_google/engine/virtual_engine_factory.py +++ b/cirq-google/cirq_google/engine/virtual_engine_factory.py @@ -401,12 +401,12 @@ def create_default_noisy_quantum_virtual_machine( """ if simulator_class is None: - try: # coverage: ignore + try: # pragma: no cover import qsimcirq # type: ignore - simulator_class = qsimcirq.QSimSimulator # coverage: ignore + simulator_class = qsimcirq.QSimSimulator # pragma: no cover except ImportError: - simulator_class = cirq.Simulator # coverage: ignore + simulator_class = cirq.Simulator # pragma: no cover calibration = load_median_device_calibration(processor_id) noise_properties = noise_properties_from_calibration(calibration) diff --git a/cirq-google/cirq_google/serialization/circuit_serializer_test.py b/cirq-google/cirq_google/serialization/circuit_serializer_test.py index 0db07c3e36d..107bf70004a 100644 --- a/cirq-google/cirq_google/serialization/circuit_serializer_test.py +++ b/cirq-google/cirq_google/serialization/circuit_serializer_test.py @@ -576,10 +576,10 @@ def test_serialize_op_bad_operation(): class NullOperation(cirq.Operation): @property def qubits(self): - return tuple() # coverage: ignore + return tuple() # pragma: no cover def with_qubits(self, *qubits): - return self # coverage: ignore + return self # pragma: no cover null_op = NullOperation() with pytest.raises(ValueError, match='Cannot serialize op'): diff --git a/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset_test.py b/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset_test.py index 6d32114602b..d3cd62056b9 100644 --- a/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset_test.py +++ b/cirq-google/cirq_google/transformers/target_gatesets/sycamore_gateset_test.py @@ -244,8 +244,7 @@ def qubits(self): return self._qubits def with_qubits(self, *new_qubits): - # coverage: ignore - return UnknownOperation(self._qubits) + return UnknownOperation(self._qubits) # pragma: no cover q0 = cirq.LineQubit(0) circuit = cirq.Circuit(UnknownOperation([q0])) diff --git a/cirq-google/cirq_google/workflow/quantum_runtime.py b/cirq-google/cirq_google/workflow/quantum_runtime.py index 644f6b94ef0..33672628163 100644 --- a/cirq-google/cirq_google/workflow/quantum_runtime.py +++ b/cirq-google/cirq_google/workflow/quantum_runtime.py @@ -69,7 +69,7 @@ def _try_tuple(k: Any) -> Any: """If we serialize a dictionary that had tuple keys, they get turned to json lists.""" if isinstance(k, list): return tuple(k) - return k # coverage: ignore + return k # pragma: no cover @dataclasses.dataclass @@ -259,8 +259,7 @@ def execute( run_id = rt_config.run_id # base_data_dir handling. - if not base_data_dir: - # coverage: ignore + if not base_data_dir: # pragma: no cover raise ValueError("Please provide a non-empty `base_data_dir`.") sampler = rt_config.processor_record.get_sampler() diff --git a/cirq-google/cirq_google/workflow/quantum_runtime_test.py b/cirq-google/cirq_google/workflow/quantum_runtime_test.py index 9b35fc5085a..9b7d8ad9185 100644 --- a/cirq-google/cirq_google/workflow/quantum_runtime_test.py +++ b/cirq-google/cirq_google/workflow/quantum_runtime_test.py @@ -80,7 +80,7 @@ def rt_config(request): target_gateset=cirq.CZTargetGateset(), ) - raise ValueError(f"Unknown flavor {request}") # coverage: ignore + raise ValueError(f"Unknown flavor {request}") # pragma: no cover def test_quantum_runtime_configuration_sampler(rt_config): diff --git a/cirq-google/cirq_google/workflow/qubit_placement.py b/cirq-google/cirq_google/workflow/qubit_placement.py index 800bf67fe4c..5b667b6c6cc 100644 --- a/cirq-google/cirq_google/workflow/qubit_placement.py +++ b/cirq-google/cirq_google/workflow/qubit_placement.py @@ -202,8 +202,7 @@ def _from_json_dict_(cls, **kwargs) -> 'HardcodedQubitPlacer': def __eq__(self, other): if not isinstance(other, HardcodedQubitPlacer): - # coverage: ignore - return False + return False # pragma: no cover return self._mapping == other._mapping diff --git a/cirq-ionq/cirq_ionq/ionq_client.py b/cirq-ionq/cirq_ionq/ionq_client.py index 3049649a887..6ce838df79d 100644 --- a/cirq-ionq/cirq_ionq/ionq_client.py +++ b/cirq-ionq/cirq_ionq/ionq_client.py @@ -345,8 +345,8 @@ def _make_request( error = {} try: error = response.json() - except jd.JSONDecodeError: # coverage: ignore - pass # coverage: ignore + except jd.JSONDecodeError: # pragma: no cover + pass # pragma: no cover raise ionq_exceptions.IonQException( 'Non-retry-able error making request to IonQ API. ' f'Request Body: {json} ' diff --git a/cirq-ionq/cirq_ionq/json_resolver_cache.py b/cirq-ionq/cirq_ionq/json_resolver_cache.py index 3e09804fc34..bcf0f66fa55 100644 --- a/cirq-ionq/cirq_ionq/json_resolver_cache.py +++ b/cirq-ionq/cirq_ionq/json_resolver_cache.py @@ -19,8 +19,8 @@ from cirq.protocols.json_serialization import ObjectFactory -@functools.lru_cache() # coverage: ignore -def _class_resolver_dictionary() -> Dict[str, ObjectFactory]: # coverage: ignore +@functools.lru_cache() # pragma: no cover +def _class_resolver_dictionary() -> Dict[str, ObjectFactory]: # pragma: no cover return { "GPIGate": cirq_ionq.GPIGate, "GPI2Gate": cirq_ionq.GPI2Gate, diff --git a/cirq-rigetti/cirq_rigetti/_qcs_api_client_decorator.py b/cirq-rigetti/cirq_rigetti/_qcs_api_client_decorator.py index 9ce07efd66c..587389c9880 100644 --- a/cirq-rigetti/cirq_rigetti/_qcs_api_client_decorator.py +++ b/cirq-rigetti/cirq_rigetti/_qcs_api_client_decorator.py @@ -36,8 +36,7 @@ def wrapper(*args, **kwargs): if 'client' in kwargs: return function(*args, **kwargs) - with build_sync_client() as client: # coverage: ignore - # coverage: ignore + with build_sync_client() as client: # pragma: no cover kwargs['client'] = client return function(*args, **kwargs) diff --git a/cirq-rigetti/cirq_rigetti/aspen_device.py b/cirq-rigetti/cirq_rigetti/aspen_device.py index dab44d179e0..b6d3b5f2684 100644 --- a/cirq-rigetti/cirq_rigetti/aspen_device.py +++ b/cirq-rigetti/cirq_rigetti/aspen_device.py @@ -126,8 +126,7 @@ def _aspen_qubit_index(self, valid_qubit: cirq.Qid) -> int: if isinstance(valid_qubit, (OctagonalQubit, AspenQubit)): return valid_qubit.index - else: - # coverage: ignore + else: # pragma: no cover raise UnsupportedQubit(f'unsupported Qid type {type(valid_qubit)}') def validate_qubit(self, qubit: 'cirq.Qid') -> None: @@ -182,8 +181,7 @@ def validate_qubit(self, qubit: 'cirq.Qid') -> None: ) return - else: - # coverage: ignore + else: # pragma: no cover raise UnsupportedQubit(f'unsupported Qid type {type(qubit)}') def validate_operation(self, operation: 'cirq.Operation') -> None: @@ -233,7 +231,7 @@ def _from_json_dict_(cls, isa, **kwargs): return cls(isa=InstructionSetArchitecture.from_dict(isa)) -@_provide_default_client +@_provide_default_client # pragma: no cover def get_rigetti_qcs_aspen_device( quantum_processor_id: str, client: Optional[httpx.Client] ) -> RigettiQCSAspenDevice: @@ -252,7 +250,6 @@ def get_rigetti_qcs_aspen_device( set and architecture. """ - # coverage: ignore isa = cast( InstructionSetArchitecture, get_instruction_set_architecture( diff --git a/cirq-rigetti/cirq_rigetti/conftest.py b/cirq-rigetti/cirq_rigetti/conftest.py index 1fa6ce3a5ce..3834fa063c3 100644 --- a/cirq-rigetti/cirq_rigetti/conftest.py +++ b/cirq-rigetti/cirq_rigetti/conftest.py @@ -31,8 +31,7 @@ import numpy as np -def pytest_collection_modifyitems(config, items): - # coverage: ignore +def pytest_collection_modifyitems(config, items): # pragma: no cover # do not skip integration tests if --rigetti-integration option passed if config.getoption('--rigetti-integration'): return diff --git a/cirq-rigetti/cirq_rigetti/json_resolver_cache.py b/cirq-rigetti/cirq_rigetti/json_resolver_cache.py index 912f7694c1b..08b63310ead 100644 --- a/cirq-rigetti/cirq_rigetti/json_resolver_cache.py +++ b/cirq-rigetti/cirq_rigetti/json_resolver_cache.py @@ -19,8 +19,8 @@ from cirq.protocols.json_serialization import ObjectFactory -@functools.lru_cache() # coverage: ignore -def _class_resolver_dictionary() -> Dict[str, ObjectFactory]: # coverage: ignore +@functools.lru_cache() # pragma: no cover +def _class_resolver_dictionary() -> Dict[str, ObjectFactory]: # pragma: no cover return { 'RigettiQCSAspenDevice': cirq_rigetti.RigettiQCSAspenDevice, 'AspenQubit': cirq_rigetti.AspenQubit, diff --git a/cirq-rigetti/cirq_rigetti/json_test_data/spec.py b/cirq-rigetti/cirq_rigetti/json_test_data/spec.py index 088f51c5543..3f4e6092acb 100644 --- a/cirq-rigetti/cirq_rigetti/json_test_data/spec.py +++ b/cirq-rigetti/cirq_rigetti/json_test_data/spec.py @@ -19,7 +19,6 @@ from cirq.testing.json import ModuleJsonTestSpec -# coverage: ignore TestSpec = ModuleJsonTestSpec( name="cirq_rigetti", packages=[cirq_rigetti], diff --git a/cirq-rigetti/cirq_rigetti/quil_output.py b/cirq-rigetti/cirq_rigetti/quil_output.py index 954aa571f34..ae246ae435f 100644 --- a/cirq-rigetti/cirq_rigetti/quil_output.py +++ b/cirq-rigetti/cirq_rigetti/quil_output.py @@ -428,10 +428,9 @@ def fallback(op): # Following code is a safety measure # Could not find a gate that doesn't decompose into a gate # with a _quil_ implementation - # coverage: ignore - if len(op.qubits) == 1: + if len(op.qubits) == 1: # pragma: no cover return QuilOneQubitGate(mat).on(*op.qubits) - return QuilTwoQubitGate(mat).on(*op.qubits) + return QuilTwoQubitGate(mat).on(*op.qubits) # pragma: no cover def on_stuck(bad_op): return ValueError(f'Cannot output operation as QUIL: {bad_op!r}') diff --git a/cirq-rigetti/cirq_rigetti/service.py b/cirq-rigetti/cirq_rigetti/service.py index b84fe94529a..308cf4626b9 100644 --- a/cirq-rigetti/cirq_rigetti/service.py +++ b/cirq-rigetti/cirq_rigetti/service.py @@ -107,7 +107,7 @@ def sampler(self) -> RigettiQCSSampler: @_provide_default_client def list_quantum_processors( client: Optional[httpx.Client], - ) -> ListQuantumProcessorsResponse: # coverage: ignore + ) -> ListQuantumProcessorsResponse: # pragma: no cover """Retrieve a list of available Rigetti quantum processors. Args: @@ -140,8 +140,7 @@ def get_quilt_calibrations( A qcs_api_client.models.GetQuiltCalibrationsResponse containing the device calibrations. """ - # coverage: ignore - return cast( + return cast( # pragma: no cover GetQuiltCalibrationsResponse, get_quilt_calibrations(client=client, quantum_processor_id=quantum_processor_id).parsed, ) @@ -150,7 +149,7 @@ def get_quilt_calibrations( @_provide_default_client def get_instruction_set_architecture( quantum_processor_id: str, client: Optional[httpx.Client] - ) -> InstructionSetArchitecture: # coverage: ignore + ) -> InstructionSetArchitecture: # pragma: no cover """Retrieve the Instruction Set Architecture of a QuantumProcessor by ID. This includes site specific operations and native gate capabilities. @@ -164,7 +163,6 @@ def get_instruction_set_architecture( Returns: A qcs_api_client.models.InstructionSetArchitecture containing the device specification. """ - # coverage: ignore return cast( InstructionSetArchitecture, get_instruction_set_architecture( diff --git a/cirq-rigetti/cirq_rigetti/service_test.py b/cirq-rigetti/cirq_rigetti/service_test.py index 27697fdaa43..32302ac4663 100644 --- a/cirq-rigetti/cirq_rigetti/service_test.py +++ b/cirq-rigetti/cirq_rigetti/service_test.py @@ -20,7 +20,7 @@ def test_rigetti_qcs_service_api_call(): class Response(httpx.Response): def iter_bytes(self, chunk_size: Optional[int] = None) -> Iterator[bytes]: - yield b"{\"quantumProcessors\": [{\"id\": \"Aspen-8\"}]}" # pragma: nocover + yield b"{\"quantumProcessors\": [{\"id\": \"Aspen-8\"}]}" # pragma: no cover class Transport(httpx.BaseTransport): def handle_request(self, request: httpx.Request) -> httpx.Response: diff --git a/dev_tools/import_test.py b/dev_tools/import_test.py index e6d78a62d87..cfaa4860c4e 100755 --- a/dev_tools/import_test.py +++ b/dev_tools/import_test.py @@ -211,11 +211,9 @@ def test_no_circular_imports(): before in an earlier test but this test needs to control the import process. """ status = subprocess.call([sys.executable, __file__]) - if status == FAIL_EXIT_CODE: - # coverage: ignore + if status == FAIL_EXIT_CODE: # pragma: no cover raise Exception('Invalid import. See captured output for details.') - elif status != 0: - # coverage: ignore + elif status != 0: # pragma: no cover raise RuntimeError('Error in subprocess') diff --git a/dev_tools/incremental_coverage.py b/dev_tools/incremental_coverage.py index dc7b833b046..71f2c53d1d9 100644 --- a/dev_tools/incremental_coverage.py +++ b/dev_tools/incremental_coverage.py @@ -54,7 +54,7 @@ # Body of mypy Protocol methods. r'\.\.\.', ] -EXPLICIT_OPT_OUT_COMMENT = '#coverage:ignore' +EXPLICIT_OPT_OUT_PATTERN = r'#\s*pragma:\s*no cover\s*$' def diff_to_new_interesting_lines(unified_diff_lines: List[str]) -> Dict[int, str]: @@ -194,23 +194,21 @@ def determine_ignored_lines(content: str) -> Set[int]: lines = content.split('\n') result: List[int] = [] + explicit_opt_out_regexp = re.compile(EXPLICIT_OPT_OUT_PATTERN) i = 0 while i < len(lines): line = lines[i] - # Drop spacing, including internal spacing within the comment. - joined_line = re.sub(r'\s+', '', line) - if any(re.match(pat, line) for pat in IGNORED_BLOCK_PATTERNS): end = naive_find_end_of_scope(lines, i + 1) result.extend(range(i, end)) i = end - elif joined_line == EXPLICIT_OPT_OUT_COMMENT: + elif explicit_opt_out_regexp.match(line.strip()): # Ignore the rest of a block. end = naive_find_end_of_scope(lines, i) result.extend(range(i, end)) i = end - elif joined_line.endswith(EXPLICIT_OPT_OUT_COMMENT): + elif explicit_opt_out_regexp.search(line): # Ignore a single line. result.append(i) i += 1 diff --git a/dev_tools/incremental_coverage_test.py b/dev_tools/incremental_coverage_test.py index 2fe0aec654a..ad36da6a66f 100644 --- a/dev_tools/incremental_coverage_test.py +++ b/dev_tools/incremental_coverage_test.py @@ -18,12 +18,12 @@ def test_determine_ignored_lines(): f = incremental_coverage.determine_ignored_lines - assert f("a = 0 # coverage: ignore") == {1} + assert f("a = 0 # pragma: no cover") == {1} assert ( f( """ - a = 0 # coverage: ignore + a = 0 # pragma: no cover b = 0 """ ) @@ -34,7 +34,7 @@ def test_determine_ignored_lines(): f( """ a = 0 - b = 0 # coverage: ignore + b = 0 # pragma: no cover """ ) == {3} @@ -43,8 +43,8 @@ def test_determine_ignored_lines(): assert ( f( """ - a = 0 # coverage: ignore - b = 0 # coverage: ignore + a = 0 # pragma: no cover + b = 0 # pragma: no cover """ ) == {2, 3} @@ -54,7 +54,7 @@ def test_determine_ignored_lines(): f( """ if True: - a = 0 # coverage: ignore + a = 0 # pragma: no cover b = 0 """ @@ -66,7 +66,7 @@ def test_determine_ignored_lines(): f( """ if True: - # coverage: ignore + # pragma: no cover a = 0 b = 0 @@ -79,7 +79,7 @@ def test_determine_ignored_lines(): f( """ if True: - # coverage: ignore + # pragma: no cover a = 0 b = 0 @@ -93,7 +93,7 @@ def test_determine_ignored_lines(): f( """ if True: - # coverage: ignore + # pragma: no cover a = 0 b = 0 @@ -109,12 +109,12 @@ def test_determine_ignored_lines(): """ if True: while False: - # coverage: ignore + # pragma: no cover a = 0 b = 0 else: - c = 0 # coverage: ignore + c = 0 # pragma: no cover """ ) == {4, 5, 6, 9} @@ -123,20 +123,20 @@ def test_determine_ignored_lines(): assert ( f( """ - a = 2#coverage:ignore - a = 3 #coverage:ignore - a = 4# coverage:ignore - a = 5#coverage :ignore - a = 6#coverage: ignore - a = 7#coverage: ignore\t - a = 8#coverage:\tignore\t + a = 2#pragma:no cover + a = 3 #pragma:no cover + a = 4# pragma:no cover + a = 5#pragma :no cover + a = 6#pragma: no cover + a = 7#pragma: no cover\t + a = 8#pragma:\tno cover\t b = 1 # no cover b = 2 # coverage: definitely b = 3 # lint: ignore """ ) - == {2, 3, 4, 5, 6, 7, 8} + == {2, 3, 4, 6, 7, 8} ) assert ( diff --git a/dev_tools/modules.py b/dev_tools/modules.py index c18c2c48f03..b684300955f 100644 --- a/dev_tools/modules.py +++ b/dev_tools/modules.py @@ -319,4 +319,4 @@ def main(argv: List[str]): if __name__ == '__main__': - main(sys.argv[1:]) # coverage: ignore + main(sys.argv[1:]) # pragma: no cover diff --git a/docs/dev/modules.md b/docs/dev/modules.md index c92ad1ce4b0..b822384c055 100644 --- a/docs/dev/modules.md +++ b/docs/dev/modules.md @@ -51,8 +51,8 @@ To setup a new module follow these steps: 1. Add the `/json_resolver_cache.py` file ```python - @functools.lru_cache() # coverage: ignore - def _class_resolver_dictionary() -> Dict[str, ObjectFactory]: # coverage: ignore + @functools.lru_cache() # pragma: no cover + def _class_resolver_dictionary() -> Dict[str, ObjectFactory]: # pragma: no cover return {} ``` 2. Register the resolver cache - at _the end_ of the `/__init__.py`: diff --git a/examples/heatmaps.py b/examples/heatmaps.py index 772eb3174a5..60637651873 100644 --- a/examples/heatmaps.py +++ b/examples/heatmaps.py @@ -38,10 +38,9 @@ def two_qubit_interaction_heatmap(): def main(): - # coverage: ignore single_qubit_heatmap() two_qubit_interaction_heatmap() -if __name__ == '__main__': +if __name__ == '__main__': # pragma: no cover main() diff --git a/examples/shors_code.py b/examples/shors_code.py index 8d717ebad25..7fe2c1d50c2 100644 --- a/examples/shors_code.py +++ b/examples/shors_code.py @@ -107,9 +107,7 @@ def correct(self): ) -if __name__ == '__main__': - # coverage: ignore - +if __name__ == '__main__': # pragma: no cover # create circuit with 9 physical qubits code = OneQubitShorsCode() diff --git a/examples/two_qubit_gate_compilation.py b/examples/two_qubit_gate_compilation.py index 16ccb216cb1..2dd1a9e3260 100644 --- a/examples/two_qubit_gate_compilation.py +++ b/examples/two_qubit_gate_compilation.py @@ -75,7 +75,7 @@ def main(samples: int = 1000, max_infidelity: float = 0.01): if result.success: infidelities.append(infidelity) else: - failed_infidelities.append(infidelity) # coverage: ignore + failed_infidelities.append(infidelity) # pragma: no cover t_comp = time() - start print(f'Gate compilation time : {t_comp:.3f} seconds ({t_comp / samples:.4f} s per gate)') @@ -83,8 +83,7 @@ def main(samples: int = 1000, max_infidelity: float = 0.01): infidelities_arr = np.array(infidelities) failed_infidelities_arr = np.array(failed_infidelities) - if np.size(failed_infidelities_arr): - # coverage: ignore + if np.size(failed_infidelities_arr): # pragma: no cover print(f'Number of "failed" compilations: {np.size(failed_infidelities_arr)}.') print(f'Maximum infidelity of "failed" compilation: {np.max(failed_infidelities_arr)}') diff --git a/rtd_docs/conf.py b/rtd_docs/conf.py index e2445235700..8bf090ad79e 100644 --- a/rtd_docs/conf.py +++ b/rtd_docs/conf.py @@ -1,4 +1,4 @@ -# coverage: ignore +# pragma: no cover # The content for all documentation lives in ../docs. That folder is # following the structure for the Google Quantum site configured for the