From c058f05cb8702821286d4b322963765eaeed25f1 Mon Sep 17 00:00:00 2001 From: Matthew Treinish Date: Wed, 4 Aug 2021 12:47:49 -0400 Subject: [PATCH] Fix test deprecation warnings and call parent's setUpClass In Qiskit/qiskit-terra#6753 the base test classes were fixed to assert that setUp and setUpClass in the base test class are always called. This is necessary to ensure that all the warning assertions always work. However this change had the unintended side effect of causing Aer's CI to fail because it wasn't calling super().setUpClass(). This commit makes this change to fix that failure. However, because now we're running enforcement that tests can't raise unhandled DeprecationWarnings a few spots in the tests were emitting deprecation warnings. The deprecated syntax is either fixed or if it's testing something in Aer that's deprecated an assertion on that warning is added to fix the failure. --- .../backends/qasm_simulator/qasm_snapshot.py | 10 ++-- .../terra/backends/test_parameterized_qobj.py | 4 +- test/terra/common.py | 1 + .../test_snapshot_expectation_value.py | 44 +++++++------- .../extensions/test_snapshot_probabilities.py | 57 +++++++++++-------- test/terra/noise/test_standard_errors.py | 8 +-- .../pulse/test_duffing_model_generators.py | 18 +++--- test/terra/utils/mock.py | 13 +++-- test/terra/utils/multiplexer.py | 12 +++- 9 files changed, 94 insertions(+), 73 deletions(-) diff --git a/test/terra/backends/qasm_simulator/qasm_snapshot.py b/test/terra/backends/qasm_simulator/qasm_snapshot.py index 4a2fdee281..28b237ccc5 100644 --- a/test/terra/backends/qasm_simulator/qasm_snapshot.py +++ b/test/terra/backends/qasm_simulator/qasm_snapshot.py @@ -206,12 +206,12 @@ def stabilizes_statevector(stabilizer, statevector): # Get stabilizer and destabilizers and convert to sets for stab in stabilizer: if stab[0] == '-': - pauli_mat = -1 * Pauli.from_label(stab[1:]).to_matrix() + pauli_mat = -1 * Pauli(stab[1:]).to_matrix() else: - pauli_mat = Pauli.from_label(stab).to_matrix() - val = statevector.conj().dot(pauli_mat.dot(statevector)) - if not np.isclose(val, 1): - return False + pauli_mat = Pauli(stab).to_matrix() + val = statevector.conj().dot(pauli_mat.dot(statevector)) + if not np.isclose(val, 1): + return False return True def test_snapshot_stabilizer_pre_measure_det(self): diff --git a/test/terra/backends/test_parameterized_qobj.py b/test/terra/backends/test_parameterized_qobj.py index f56d9ebc0f..ff37073afb 100644 --- a/test/terra/backends/test_parameterized_qobj.py +++ b/test/terra/backends/test_parameterized_qobj.py @@ -83,7 +83,7 @@ def test_parameterized_qobj_qasm_snapshot_expval(self): measure=True, snapshot=True) self.assertIn('parameterizations', qobj.to_dict()['config']) - job = backend.run(qobj, self.BACKEND_OPTS) + job = backend.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) num_circs = len(result.to_dict()['results']) @@ -113,7 +113,7 @@ def test_parameterized_qobj_statevector(self): measure=False, snapshot=False) self.assertIn('parameterizations', qobj.to_dict()['config']) - job = backend.run(qobj, self.BACKEND_OPTS) + job = backend.run(qobj, **self.BACKEND_OPTS) result = job.result() success = getattr(result, 'success', False) num_circs = len(result.to_dict()['results']) diff --git a/test/terra/common.py b/test/terra/common.py index 8346a8bf87..2bc3b2755e 100644 --- a/test/terra/common.py +++ b/test/terra/common.py @@ -50,6 +50,7 @@ def setUp(self): @classmethod def setUpClass(cls): + super().setUpClass() cls.moduleName = os.path.splitext(inspect.getfile(cls))[0] cls.log = logging.getLogger(cls.__name__) diff --git a/test/terra/extensions/test_snapshot_expectation_value.py b/test/terra/extensions/test_snapshot_expectation_value.py index 9813f00e99..6e0009e2a0 100644 --- a/test/terra/extensions/test_snapshot_expectation_value.py +++ b/test/terra/extensions/test_snapshot_expectation_value.py @@ -43,7 +43,7 @@ def test_snapshot_label_raises(self): def test_snapshot_name(self): """Test snapshot instruction has correct name""" - for op in [Pauli.from_label('X'), Operator([[0, 1], [1, 0]])]: + for op in [Pauli('X'), Operator([[0, 1], [1, 0]])]: instrs = [ SnapshotExpectationValue('snap', op).assemble(), self.snapshot_circuit_instr(1, 'snap', op, [0]) @@ -54,7 +54,7 @@ def test_snapshot_name(self): def test_snapshot_label(self): """Test snapshot instruction has correct label""" - for op in [Pauli.from_label('X'), Operator([[0, 1], [1, 0]])]: + for op in [Pauli('X'), Operator([[0, 1], [1, 0]])]: for label in ['snap0', 'snap1']: instrs = [ SnapshotExpectationValue(label, op).assemble(), @@ -69,7 +69,7 @@ def test_snapshot_pauli_type(self): pauli_ops = [ [[1, 'I'], [0.5, 'X'], [0.25, 'Y'], [-3, 'Z']], [[1j, 'I'], [0.5j, 'X'], [0.25j, 'Y'], [-3j, 'Z']], - [[0.5j, Pauli.from_label('X')], [-0.5j, Pauli.from_label('Z')]] + [[0.5j, Pauli('X')], [-0.5j, Pauli('Z')]] ] for op in pauli_ops: # standard @@ -97,14 +97,15 @@ def test_snapshot_pauli_type(self): self.assertTrue(hasattr(instr, 'snapshot_type')) self.assertEqual(instr.snapshot_type, 'expectation_value_pauli_single_shot') # Variance - instrs = [ - SnapshotExpectationValue('snap', op, - single_shot=False, - variance=True).assemble(), - self.snapshot_circuit_instr(1, 'snap', op, [0], - single_shot=False, - variance=True) - ] + with self.assertWarns(DeprecationWarning): + instrs = [ + SnapshotExpectationValue('snap', op, + single_shot=False, + variance=True).assemble(), + self.snapshot_circuit_instr(1, 'snap', op, [0], + single_shot=False, + variance=True) + ] for instr in instrs: self.assertTrue(hasattr(instr, 'snapshot_type')) self.assertEqual(instr.snapshot_type, 'expectation_value_pauli_with_variance') @@ -114,7 +115,7 @@ def test_snapshot_matrix_type(self): matrix_ops = [ numpy.eye(2), numpy.array([[0, 1j], [-1j, 0]]), - Operator(Pauli.from_label('Z')) + Operator(Pauli('Z')) ] for op in matrix_ops: # standard @@ -142,14 +143,15 @@ def test_snapshot_matrix_type(self): self.assertTrue(hasattr(instr, 'snapshot_type')) self.assertEqual(instr.snapshot_type, 'expectation_value_matrix_single_shot') # Variance - instrs = [ - SnapshotExpectationValue('snap', op, - single_shot=False, - variance=True).assemble(), - self.snapshot_circuit_instr(1, 'snap', op, [0], - single_shot=False, - variance=True) - ] + with self.assertWarns(DeprecationWarning): + instrs = [ + SnapshotExpectationValue('snap', op, + single_shot=False, + variance=True).assemble(), + self.snapshot_circuit_instr(1, 'snap', op, [0], + single_shot=False, + variance=True) + ] for instr in instrs: self.assertTrue(hasattr(instr, 'snapshot_type')) self.assertEqual(instr.snapshot_type, 'expectation_value_matrix_with_variance') @@ -157,7 +159,7 @@ def test_snapshot_matrix_type(self): def test_snapshot_specific_qubits(self): """Test snapshot instruction has correct qubits.""" for qubits in [[0], [0, 2], [1, 3, 0]]: - pauli = Pauli.from_label(len(qubits) * 'X') + pauli = Pauli(len(qubits) * 'X') instrs = [ self.snapshot_circuit_instr(5, 'snap', pauli, qubits), self.snapshot_circuit_instr(5, 'snap', Operator(pauli), qubits) diff --git a/test/terra/extensions/test_snapshot_probabilities.py b/test/terra/extensions/test_snapshot_probabilities.py index d10e930cf1..4482a679aa 100644 --- a/test/terra/extensions/test_snapshot_probabilities.py +++ b/test/terra/extensions/test_snapshot_probabilities.py @@ -23,11 +23,14 @@ class TestSnapshotProbabilitiesExtension(QiskitAerTestCase): """SnapshotProbabilities extension tests""" - @staticmethod - def snapshot_circuit_instr(circ_qubits, label, qubits, variance=False): + def snapshot_circuit_instr(self, circ_qubits, label, qubits, variance=False): """Return QobjInstruction for circuit monkey patch method.""" circuit = QuantumCircuit(circ_qubits) - circuit.snapshot_probabilities(label, qubits, variance) + if variance: + with self.assertWarns(DeprecationWarning): + circuit.snapshot_probabilities(label, qubits, variance) + else: + circuit.snapshot_probabilities(label, qubits, variance) qobj = assemble(circuit) instr = qobj.experiments[0].instructions[0] return instr @@ -38,12 +41,13 @@ def test_snapshot_label_raises(self): def test_snapshot_name(self): """Test snapshot instruction has correct name""" - instrs = [ - SnapshotProbabilities('snap', 1, False).assemble(), - SnapshotProbabilities('snap', 1, True).assemble(), - self.snapshot_circuit_instr(1, 'snap', [0], False), - self.snapshot_circuit_instr(1, 'snap', [0], True) - ] + with self.assertWarns(DeprecationWarning): + instrs = [ + SnapshotProbabilities('snap', 1, False).assemble(), + SnapshotProbabilities('snap', 1, True).assemble(), + self.snapshot_circuit_instr(1, 'snap', [0], False), + self.snapshot_circuit_instr(1, 'snap', [0], True) + ] for instr in instrs: self.assertTrue(hasattr(instr, 'name')) self.assertEqual(instr.name, 'snapshot') @@ -59,10 +63,11 @@ def test_snapshot_type(self): self.assertTrue(hasattr(instr, 'snapshot_type')) self.assertEqual(instr.snapshot_type, 'probabilities') # with variance - instrs = [ - SnapshotProbabilities('snap', 1, True).assemble(), - self.snapshot_circuit_instr(1, 'snap', [0], True) - ] + with self.assertWarns(DeprecationWarning): + instrs = [ + SnapshotProbabilities('snap', 1, True).assemble(), + self.snapshot_circuit_instr(1, 'snap', [0], True) + ] for instr in instrs: self.assertTrue(hasattr(instr, 'snapshot_type')) self.assertEqual(instr.snapshot_type, 'probabilities_with_variance') @@ -70,12 +75,13 @@ def test_snapshot_type(self): def test_snapshot_label(self): """Test snapshot instruction has correct label""" for label in ['snap0', 'snap1']: - instrs = [ - SnapshotProbabilities(label, 1, False).assemble(), - SnapshotProbabilities(label, 1, True).assemble(), - self.snapshot_circuit_instr(1, label, [0], False), - self.snapshot_circuit_instr(1, label, [0], True) - ] + with self.assertWarns(DeprecationWarning): + instrs = [ + SnapshotProbabilities(label, 1, False).assemble(), + SnapshotProbabilities(label, 1, True).assemble(), + self.snapshot_circuit_instr(1, label, [0], False), + self.snapshot_circuit_instr(1, label, [0], True) + ] for instr in instrs: self.assertTrue(hasattr(instr, 'label')) self.assertEqual(instr.label, label) @@ -83,12 +89,13 @@ def test_snapshot_label(self): def test_snapshot_all_qubits(self): """Test snapshot instruction has correct qubits.""" for j in range(1, 5): - instrs = [ - SnapshotProbabilities('snap', j, False).assemble(), - SnapshotProbabilities('snap', j, True).assemble(), - self.snapshot_circuit_instr(j, 'snap', range(j), True), - self.snapshot_circuit_instr(j, 'snap', range(j), False) - ] + with self.assertWarns(DeprecationWarning): + instrs = [ + SnapshotProbabilities('snap', j, False).assemble(), + SnapshotProbabilities('snap', j, True).assemble(), + self.snapshot_circuit_instr(j, 'snap', range(j), True), + self.snapshot_circuit_instr(j, 'snap', range(j), False) + ] for instr in instrs: self.assertTrue(hasattr(instr, 'qubits')) self.assertEqual(instr.qubits, list(range(j))) diff --git a/test/terra/noise/test_standard_errors.py b/test/terra/noise/test_standard_errors.py index 84972b9029..eaef7c2dce 100644 --- a/test/terra/noise/test_standard_errors.py +++ b/test/terra/noise/test_standard_errors.py @@ -137,7 +137,7 @@ def test_pauli_error_1q_gate_from_string(self): def test_pauli_error_1q_unitary_from_pauli(self): """Test single-qubit pauli error as unitary qobj from Pauli obj""" - paulis = [Pauli.from_label(s) for s in ['I', 'X', 'Y', 'Z']] + paulis = [Pauli(s) for s in ['I', 'X', 'Y', 'Z']] probs = [0.4, 0.3, 0.2, 0.1] error = pauli_error(zip(paulis, probs), standard_gates=False) @@ -162,7 +162,7 @@ def test_pauli_error_1q_unitary_from_pauli(self): def test_pauli_error_1q_gate_from_pauli(self): """Test single-qubit pauli error as gate qobj from Pauli obj""" - paulis = [Pauli.from_label(s) for s in ['I', 'X', 'Y', 'Z']] + paulis = [Pauli(s) for s in ['I', 'X', 'Y', 'Z']] probs = [0.4, 0.3, 0.2, 0.1] error = pauli_error(zip(paulis, probs), standard_gates=True) @@ -258,7 +258,7 @@ def test_pauli_error_2q_gate_from_string_1qonly(self): def test_pauli_error_2q_unitary_from_pauli(self): """Test two-qubit pauli error as unitary qobj from Pauli obj""" - paulis = [Pauli.from_label(s) for s in ['XY', 'YZ', 'ZX']] + paulis = [Pauli(s) for s in ['XY', 'YZ', 'ZX']] probs = [0.5, 0.3, 0.2] error = pauli_error(zip(paulis, probs), standard_gates=False) @@ -279,7 +279,7 @@ def test_pauli_error_2q_unitary_from_pauli(self): def test_pauli_error_2q_gate_from_pauli(self): """Test two-qubit pauli error as gate qobj from Pauli obj""" - paulis = [Pauli.from_label(s) for s in ['XZ', 'YX', 'ZY']] + paulis = [Pauli(s) for s in ['XZ', 'YX', 'ZY']] probs = [0.5, 0.3, 0.2] error = pauli_error(zip(paulis, probs), standard_gates=True) diff --git a/test/terra/pulse/test_duffing_model_generators.py b/test/terra/pulse/test_duffing_model_generators.py index b18067a659..53eeafaea3 100644 --- a/test/terra/pulse/test_duffing_model_generators.py +++ b/test/terra/pulse/test_duffing_model_generators.py @@ -77,8 +77,8 @@ def test_duffing_system_model1(self): # and then parsed O0 = self._operator_array_from_str(2, ['I', 'O']) O1 = self._operator_array_from_str(2, ['O', 'I']) - OO0 = O0@O0 - OO1 = O1@O1 + OO0 = O0 & O0 + OO1 = O1 & O1 X0 = self._operator_array_from_str(2, ['I', 'X']) X1 = self._operator_array_from_str(2, ['X', 'I']) exchange = self._operator_array_from_str(2, ['Sm', 'Sp']) + self._operator_array_from_str(2, ['Sp', 'Sm']) @@ -162,9 +162,9 @@ def test_duffing_system_model2(self): O0 = self._operator_array_from_str(3, ['I', 'I', 'O']) O1 = self._operator_array_from_str(3, ['I', 'O', 'I']) O2 = self._operator_array_from_str(3, ['O', 'I', 'I']) - OO0 = O0@O0 - OO1 = O1@O1 - OO2 = O2@O2 + OO0 = O0 & O0 + OO1 = O1 & O1 + OO2 = O2 & O2 X0 = self._operator_array_from_str(3, ['I', 'I', 'A']) + self._operator_array_from_str(3, ['I', 'I', 'C']) X1 = self._operator_array_from_str(3, ['I', 'A', 'I']) + self._operator_array_from_str(3, ['I', 'C', 'I']) X2 = self._operator_array_from_str(3, ['A', 'I', 'I']) + self._operator_array_from_str(3, ['C', 'I', 'I']) @@ -264,10 +264,10 @@ def test_duffing_system_model3(self): O1 = self._operator_array_from_str(2, ['I', 'I', 'O', 'I']) O2 = self._operator_array_from_str(2, ['I', 'O', 'I', 'I']) O3 = self._operator_array_from_str(2, ['O', 'I', 'I', 'I']) - OO0 = O0@O0 - OO1 = O1@O1 - OO2 = O2@O2 - OO3 = O3@O3 + OO0 = O0 & O0 + OO1 = O1 & O1 + OO2 = O2 & O2 + OO3 = O3 & O3 X0 = self._operator_array_from_str(2, ['I','I', 'I', 'A']) + self._operator_array_from_str(2, ['I', 'I', 'I', 'C']) X1 = self._operator_array_from_str(2, ['I', 'I', 'A', 'I']) + self._operator_array_from_str(2, ['I', 'I', 'C', 'I']) X2 = self._operator_array_from_str(2, ['I', 'A', 'I', 'I']) + self._operator_array_from_str(2, ['I', 'C', 'I', 'I']) diff --git a/test/terra/utils/mock.py b/test/terra/utils/mock.py index 1334d34c77..910643ed32 100644 --- a/test/terra/utils/mock.py +++ b/test/terra/utils/mock.py @@ -29,14 +29,14 @@ import time from qiskit.result import Result -from qiskit.providers import BaseBackend, BaseJob +from qiskit.providers import BackendV1, JobV1, Options from qiskit.providers.models import BackendProperties, BackendConfiguration from qiskit.providers.models.backendconfiguration import GateConfig from qiskit.qobj import (QasmQobj, QobjExperimentHeader, QobjHeader, QasmQobjInstruction, QasmQobjExperimentConfig, QasmQobjExperiment, QasmQobjConfig) from qiskit.providers.jobstatus import JobStatus -from qiskit.providers.baseprovider import BaseProvider +from qiskit.providers import ProviderV1 from qiskit.providers.exceptions import QiskitBackendNotFoundError from qiskit.providers.aer import AerError @@ -44,7 +44,7 @@ logger = logging.getLogger(__name__) -class FakeProvider(BaseProvider): +class FakeProvider(ProviderV1): """Dummy provider just for testing purposes. Only filtering backends by name is implemented. @@ -71,7 +71,7 @@ def __init__(self): super().__init__() -class FakeBackend(BaseBackend): +class FakeBackend(BackendV1): """This is a dummy backend just for testing purposes.""" def __init__(self, configuration, time_alive=10): @@ -107,6 +107,9 @@ def run(self, qobj): job.submit() return job + def _default_options(self): + return Options() + # pylint: disable=unused-argument def run_job(self, job_id, qobj): """Main dummy run loop""" @@ -178,7 +181,7 @@ def run_job(self, job_id, qobj): raise AerError("Mocking a failure in the QASM Simulator") -class FakeJob(BaseJob): +class FakeJob(JobV1): """Fake simulator job""" _executor = futures.ThreadPoolExecutor() diff --git a/test/terra/utils/multiplexer.py b/test/terra/utils/multiplexer.py index b25199e31f..a3973c2a16 100644 --- a/test/terra/utils/multiplexer.py +++ b/test/terra/utils/multiplexer.py @@ -1,10 +1,18 @@ import numpy as np from qiskit.circuit import Gate +class CustomMultiplexer(Gate): + + def validate_parameter(self, param): + return param + def multiplexer_multi_controlled_x(num_control): # Multi-controlled X gate multiplexer identity = np.array(np.array([[1, 0], [0, 1]], dtype=complex)) x_gate = np.array(np.array([[0, 1], [1, 0]], dtype=complex)) num_qubits = num_control + 1 - multiplexer = Gate('multiplexer', num_qubits, (2 ** num_control-1) * [identity] + [x_gate]) - return multiplexer \ No newline at end of file + multiplexer = CustomMultiplexer( + 'multiplexer', + num_qubits, (2 ** num_control-1) * [identity] + [x_gate], + ) + return multiplexer