Fix test deprecation warnings and call parent's setUpClass (#1303)

* 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.
This commit is contained in:
Matthew Treinish 2021-08-05 12:13:28 -04:00 committed by GitHub
parent 9e08552f99
commit dcff5b28f2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 100 additions and 72 deletions

View File

@ -3,4 +3,3 @@ astroid==2.3.3
six>1.10,<=1.14
numpy>=1.16.3
scipy>=1.0
cvxpy<1.1.8

View File

@ -3,7 +3,7 @@ cmake!=3.17.1,!=3.17.0
conan>=1.31.2
scikit-build>=0.11.0
asv
cvxpy>=1.0.0,<1.1.8;python_version>'3.6' and python_version<='3.8'
cvxpy>=1.0.0
pylint
pycodestyle
Sphinx>=1.8.3

View File

@ -206,9 +206,9 @@ class QasmSnapshotStabilizerTests:
# 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()
pauli_mat = Pauli(stab).to_matrix()
val = statevector.conj().dot(pauli_mat.dot(statevector))
if not np.isclose(val, 1):
return False

View File

@ -83,7 +83,7 @@ class TestParameterizedQobj(common.QiskitAerTestCase):
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 @@ class TestParameterizedQobj(common.QiskitAerTestCase):
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'])

View File

@ -25,6 +25,7 @@ from random import choice, sample
from math import pi
import numpy as np
import fixtures
import warnings
from qiskit.quantum_info import Operator, Statevector
from qiskit.quantum_info.operators.predicates import matrix_equal
@ -50,6 +51,14 @@ class QiskitAerTestCase(FullQiskitTestCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
allow_DeprecationWarning_modules = [
"cvxpy",
]
for mod in allow_DeprecationWarning_modules:
warnings.filterwarnings("default", category=DeprecationWarning, module=mod)
cls.moduleName = os.path.splitext(inspect.getfile(cls))[0]
cls.log = logging.getLogger(cls.__name__)

View File

@ -43,7 +43,7 @@ class TestSnapshotExpectationValueExtension(QiskitAerTestCase):
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 @@ class TestSnapshotExpectationValueExtension(QiskitAerTestCase):
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 @@ class TestSnapshotExpectationValueExtension(QiskitAerTestCase):
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 @@ class TestSnapshotExpectationValueExtension(QiskitAerTestCase):
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 @@ class TestSnapshotExpectationValueExtension(QiskitAerTestCase):
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 @@ class TestSnapshotExpectationValueExtension(QiskitAerTestCase):
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 @@ class TestSnapshotExpectationValueExtension(QiskitAerTestCase):
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)

View File

@ -23,11 +23,14 @@ from ..common import QiskitAerTestCase
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 @@ class TestSnapshotProbabilitiesExtension(QiskitAerTestCase):
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 @@ class TestSnapshotProbabilitiesExtension(QiskitAerTestCase):
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 @@ class TestSnapshotProbabilitiesExtension(QiskitAerTestCase):
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 @@ class TestSnapshotProbabilitiesExtension(QiskitAerTestCase):
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)))

View File

@ -137,7 +137,7 @@ class TestNoise(common.QiskitAerTestCase):
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 @@ class TestNoise(common.QiskitAerTestCase):
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 @@ class TestNoise(common.QiskitAerTestCase):
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 @@ class TestNoise(common.QiskitAerTestCase):
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)

View File

@ -77,8 +77,8 @@ class TestDuffingModelGenerators(QiskitAerTestCase):
# 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 @@ class TestDuffingModelGenerators(QiskitAerTestCase):
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 @@ class TestDuffingModelGenerators(QiskitAerTestCase):
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'])

View File

@ -29,14 +29,14 @@ from concurrent import futures
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 @@ 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.
@ -71,7 +71,7 @@ class FakeProvider(BaseProvider):
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 @@ class FakeBackend(BaseBackend):
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 @@ class FakeFailureQasmSimulator(FakeBackend):
raise AerError("Mocking a failure in the QASM Simulator")
class FakeJob(BaseJob):
class FakeJob(JobV1):
"""Fake simulator job"""
_executor = futures.ThreadPoolExecutor()

View File

@ -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