Skip to content

Commit

Permalink
Fix test deprecation warnings and call parent's setUpClass
Browse files Browse the repository at this point in the history
In Qiskit/qiskit#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.
  • Loading branch information
mtreinish committed Aug 4, 2021
1 parent 9e08552 commit c058f05
Show file tree
Hide file tree
Showing 9 changed files with 94 additions and 73 deletions.
10 changes: 5 additions & 5 deletions test/terra/backends/qasm_simulator/qasm_snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
4 changes: 2 additions & 2 deletions test/terra/backends/test_parameterized_qobj.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'])
Expand Down Expand Up @@ -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'])
Expand Down
1 change: 1 addition & 0 deletions test/terra/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__)

Expand Down
44 changes: 23 additions & 21 deletions test/terra/extensions/test_snapshot_expectation_value.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])
Expand All @@ -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(),
Expand All @@ -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
Expand Down Expand Up @@ -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')
Expand All @@ -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
Expand Down Expand Up @@ -142,22 +143,23 @@ 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')

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)
Expand Down
57 changes: 32 additions & 25 deletions test/terra/extensions/test_snapshot_probabilities.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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')
Expand All @@ -59,36 +63,39 @@ 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')

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)

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)))
Expand Down
8 changes: 4 additions & 4 deletions test/terra/noise/test_standard_errors.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand All @@ -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)

Expand Down Expand Up @@ -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)

Expand All @@ -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)

Expand Down
18 changes: 9 additions & 9 deletions test/terra/pulse/test_duffing_model_generators.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'])
Expand Down Expand Up @@ -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'])
Expand Down Expand Up @@ -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'])
Expand Down
13 changes: 8 additions & 5 deletions test/terra/utils/mock.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,22 +29,22 @@
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


logger = logging.getLogger(__name__)


class FakeProvider(BaseProvider):
class FakeProvider(ProviderV1):
"""Dummy provider just for testing purposes.
Only filtering backends by name is implemented.
Expand All @@ -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):
Expand Down Expand Up @@ -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"""
Expand Down Expand Up @@ -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()

Expand Down
12 changes: 10 additions & 2 deletions test/terra/utils/multiplexer.py
Original file line number Diff line number Diff line change
@@ -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
multiplexer = CustomMultiplexer(
'multiplexer',
num_qubits, (2 ** num_control-1) * [identity] + [x_gate],
)
return multiplexer

0 comments on commit c058f05

Please sign in to comment.