Skip to content

Commit

Permalink
Merge pull request #556 from qutech/feat/fail_on_deprecation_warnings
Browse files Browse the repository at this point in the history
Fail tests on deprecation warnings
  • Loading branch information
terrorfisch authored Mar 3, 2021
2 parents 35a10a3 + afdea88 commit 78be892
Show file tree
Hide file tree
Showing 13 changed files with 80 additions and 41 deletions.
6 changes: 6 additions & 0 deletions qupulse/expressions.py
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,9 @@ def __str__(self):
def __repr__(self):
return 'ExpressionVector({})'.format(repr(self.get_serialization_data()))

def _sympy_(self):
return sympy.NDimArray(self._expression_vector)

def __eq__(self, other):
if not isinstance(other, Expression):
other = Expression.make(other)
Expand Down Expand Up @@ -330,6 +333,9 @@ def __neg__(self) -> 'ExpressionScalar':
def __pos__(self):
return self.make(self._sympified_expression.__pos__())

def _sympy_(self):
return self._sympified_expression

@property
def original_expression(self) -> Union[str, Number]:
return self._original_expression
Expand Down
6 changes: 4 additions & 2 deletions qupulse/pulses/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ def __init__(self, value: Union[Real, numpy.ndarray, Expression, str, sympy.Expr
Args:
value: The value of the parameter
"""
warnings.warn("ConstantParameter is deprecated. Use plain number types instead", DeprecationWarning)
warnings.warn("ConstantParameter is deprecated. Use plain number types instead", DeprecationWarning,
stacklevel=2)

super().__init__()
try:
Expand Down Expand Up @@ -114,7 +115,8 @@ def __init__(self,
dependencies (Dict(str -> Parameter)): Parameter objects of the dependencies. The objects them selves must
not change but the parameters might return different values.
"""
warnings.warn("MappedParameter is deprecated. There should be no interface depending on it", DeprecationWarning)
warnings.warn("MappedParameter is deprecated. There should be no interface depending on it", DeprecationWarning,
stacklevel=2)

super().__init__()
self._expression = expression
Expand Down
20 changes: 13 additions & 7 deletions qupulse/serialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,8 @@ def list_contents(self) -> Iterable[str]:
Returns:
List of all available identifiers.
"""
warnings.warn("list_contents is deprecated. Use the property contents instead", DeprecationWarning)
warnings.warn("list_contents is deprecated. Use the property contents instead", DeprecationWarning,
stacklevel=2)
return self.contents

@property
Expand Down Expand Up @@ -308,7 +309,7 @@ def __init__(self, backend: StorageBackend) -> None:
IO functionality.
"""
warnings.warn("CachingBackend is obsolete due to PulseStorage already offering caching functionality.",
DeprecationWarning)
DeprecationWarning, stacklevel=2)
self._backend = backend
self._cache = {}

Expand Down Expand Up @@ -529,7 +530,8 @@ def get_serialization_data(self, serializer: Optional['Serializer']=None) -> Dic
storing and later reconstruction as a Python object.
"""
if serializer:
warnings.warn("{c}.get_serialization_data(*) was called with a serializer argument, indicating deprecated behavior. Please switch to the new serialization routines.".format(c=self.__class__.__name__), DeprecationWarning)
warnings.warn("{c}.get_serialization_data(*) was called with a serializer argument, indicating deprecated behavior. Please switch to the new serialization routines.".format(c=self.__class__.__name__),
DeprecationWarning, stacklevel=2)

if self.identifier:
return {self.type_identifier_name: self.get_type_identifier(), self.identifier_name: self.identifier}
Expand Down Expand Up @@ -567,7 +569,8 @@ def deserialize(cls, serializer: Optional['Serializer']=None, **kwargs) -> 'Seri
to this method.
"""
if serializer:
warnings.warn("{c}.deserialize(*) was called with a serializer argument, indicating deprecated behavior. Please switch to the new serialization routines.".format(c=cls.__name__), DeprecationWarning)
warnings.warn("{c}.deserialize(*) was called with a serializer argument, indicating deprecated behavior. Please switch to the new serialization routines.".format(c=cls.__name__),
DeprecationWarning, stacklevel=2)

return cls(**kwargs)

Expand Down Expand Up @@ -632,7 +635,8 @@ def __init__(self, storage_backend: StorageBackend) -> None:
self.__subpulses = dict() # type: Dict[str, Serializer.__FileEntry]
self.__storage_backend = storage_backend

warnings.warn("Serializer is deprecated. Please switch to the new serialization routines.", DeprecationWarning)
warnings.warn("Serializer is deprecated. Please switch to the new serialization routines.",
DeprecationWarning, stacklevel=2)

def dictify(self, serializable: Serializable) -> Union[str, Dict[str, Any]]:
"""Converts a Serializable into a dictionary representation.
Expand Down Expand Up @@ -721,7 +725,8 @@ def serialize(self, serializable: Serializable, overwrite=False) -> None:
Args:
serializable (Serializable): The Serializable to serialize and store
"""
warnings.warn("Serializer is deprecated. Please switch to the new serialization routines.", DeprecationWarning)
warnings.warn("Serializer is deprecated. Please switch to the new serialization routines.",
DeprecationWarning, stacklevel=2)
repr_ = self.__collect_dictionaries(serializable)
for identifier in repr_:
storage_identifier = identifier
Expand All @@ -742,7 +747,8 @@ def deserialize(self, representation: Union[str, Dict[str, Any]]) -> Serializabl
See also:
Serializable.deserialize
"""
warnings.warn("Serializer is deprecated. Please switch to the new serialization routines.", DeprecationWarning)
warnings.warn("Serializer is deprecated. Please switch to the new serialization routines.", DeprecationWarning,
stacklevel=2)
if isinstance(representation, str):
if representation in self.__subpulses:
return self.__subpulses[representation].serializable
Expand Down
6 changes: 6 additions & 0 deletions setup.cfg
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
[tool:pytest]
testpaths = tests tests/pulses tests/hardware tests/backward_compatibility
python_files=*_tests.py *_bug.py
filterwarnings =
# syntax is action:message_regex:category:module_regex:lineno
# we fail on all with a whitelist because a dependency might mess-up passing the correct stacklevel
error::DeprecationWarning
# pytest uses readline which uses collections.abc
ignore:Using or importing the ABCs from \'collections\' instead of from \'collections\.abc\' is deprecated:DeprecationWarning:.*readline.*
[build_sphinx]
project = 'qupulse'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import typing
import importlib.util
import sys
import warnings

from tests.hardware.tabor_simulator_based_tests import TaborSimulatorManager
from tests.hardware.dummy_devices import DummyDAC
Expand Down Expand Up @@ -158,7 +159,8 @@ def setUpClass(cls):
cls.test_state = PulseLoadingAndSequencingHelper(cls.data_folder, cls.pulse_name)

def test_1_1_deserialization(self):
self.test_state.deserialize_pulse()
with self.assertWarns(DeprecationWarning):
self.test_state.deserialize_pulse()

def test_1_2_deserialization_2018(self) -> None:
self.test_state.deserialize_pulse_2018()
Expand Down
2 changes: 1 addition & 1 deletion tests/expression_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ def test_number_comparison(self):
self.assertIs(3 >= valued, True)

def assertExpressionEqual(self, lhs: Expression, rhs: Expression):
self.assertTrue(bool(Eq(lhs.sympified_expression, rhs.sympified_expression)), '{} and {} are not equal'.format(lhs, rhs))
self.assertTrue(bool(Eq(lhs, rhs)), '{} and {} are not equal'.format(lhs, rhs))

def test_number_math(self):
a = ExpressionScalar('a')
Expand Down
2 changes: 1 addition & 1 deletion tests/hardware/zihdawg_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ def test_init(self):
def test_set_volatile_parameters(self):
mock_device = mock.Mock()

parameters = {'a': ConstantParameter(9)}
parameters = {'a': 9}
requested_changes = OrderedDict([(UserRegister.from_seqc(4), 2), (UserRegister.from_seqc(3), 6)])

expected_user_reg_calls = [mock.call(*args) for args in requested_changes.items()]
Expand Down
8 changes: 5 additions & 3 deletions tests/pulses/mapping_pulse_template_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,10 @@ def test_map_parameters(self):
template = DummyPulseTemplate(parameter_names={'foo', 'bar'})
st = MappingPulseTemplate(template, parameter_mapping={'foo': 't*k', 'bar': 't*l'})

parameters = {'t': ConstantParameter(3), 'k': ConstantParameter(2), 'l': ConstantParameter(7)}
parameters = {'t': 3, 'k': 2, 'l': 7}
values = {'foo': 6, 'bar': 21}
for k, v in st.map_parameters(parameters).items():
self.assertEqual(v.get_value(), values[k])
self.assertEqual(v, values[k])
parameters.popitem()
with self.assertRaises(ParameterNotProvidedException):
st.map_parameters(parameters)
Expand All @@ -178,7 +178,9 @@ def test_map_parameters(self):
with self.assertRaisesRegex(ValueError, "type of return value"):
st.map_parameters({})

parameters = dict(t=3, k=2, l=ConstantParameter(7))
with self.assertWarns(DeprecationWarning):
# remove if ConstantParameter is removed
parameters = dict(t=3, k=2, l=ConstantParameter(7))
with self.assertRaisesRegex(TypeError, "neither all Parameter nor Real"):
st.map_parameters(parameters)

Expand Down
37 changes: 23 additions & 14 deletions tests/pulses/parameters_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@

class ConstantParameterTest(unittest.TestCase):
def __test_valid_params(self, value: float) -> None:
constant_parameter = ConstantParameter(value)
with self.assertWarns(DeprecationWarning):
constant_parameter = ConstantParameter(value)
self.assertEqual(value, constant_parameter.get_value())

def test_float_values(self) -> None:
Expand All @@ -18,38 +19,44 @@ def test_float_values(self) -> None:
self.__test_valid_params(0.3)

def test_requires_stop(self) -> None:
constant_parameter = ConstantParameter(0.3)
with self.assertWarns(DeprecationWarning):
constant_parameter = ConstantParameter(0.3)
self.assertFalse(constant_parameter.requires_stop)

def test_repr(self) -> None:
constant_parameter = ConstantParameter(0.2)
with self.assertWarns(DeprecationWarning):
constant_parameter = ConstantParameter(0.2)
self.assertEqual("<ConstantParameter 0.2>", repr(constant_parameter))

def test_expression_value(self) -> None:
expression_str = "exp(4)*sin(pi/2)"
expression_obj = Expression(expression_str)
expression_val = expression_obj.evaluate_numeric()
param = ConstantParameter(expression_str)
self.assertEqual(expression_val, param.get_value())
param = ConstantParameter(expression_obj)
self.assertEqual(expression_val, param.get_value())
with self.assertWarns(DeprecationWarning):
param = ConstantParameter(expression_str)
self.assertEqual(expression_val, param.get_value())
param = ConstantParameter(expression_obj)
self.assertEqual(expression_val, param.get_value())

def test_invalid_expression_value(self) -> None:
expression_obj = Expression("sin(pi/2*t)")
with self.assertRaises(RuntimeError):
ConstantParameter(expression_obj)
with self.assertWarns(DeprecationWarning):
ConstantParameter(expression_obj)

def test_numpy_value(self) -> None:
import numpy as np
arr = np.array([6, 7, 8])
param = ConstantParameter(arr)
with self.assertWarns(DeprecationWarning):
param = ConstantParameter(arr)
np.array_equal(arr, param.get_value())


class MappedParameterTest(unittest.TestCase):

def test_requires_stop_and_get_value(self) -> None:
p = MappedParameter(Expression("foo + bar * hugo"))
with self.assertWarns(DeprecationWarning):
p = MappedParameter(Expression("foo + bar * hugo"))
with self.assertRaises(ParameterNotProvidedException):
p.requires_stop
with self.assertRaises(ParameterNotProvidedException):
Expand All @@ -75,13 +82,15 @@ def test_requires_stop_and_get_value(self) -> None:
self.assertEqual(1.5, p.get_value())

def test_repr(self) -> None:
p = MappedParameter(Expression("foo + bar * hugo"))
with self.assertWarns(DeprecationWarning):
p = MappedParameter(Expression("foo + bar * hugo"))
self.assertIsInstance(repr(p), str)

def test_equality(self):
p1 = MappedParameter(Expression("foo + 1"), {'foo': ConstantParameter(3)})
p2 = MappedParameter(Expression("foo + 1"), {'foo': ConstantParameter(4)})
p3 = MappedParameter(Expression("foo + 1"), {'foo': ConstantParameter(3)})
with self.assertWarns(DeprecationWarning):
p1 = MappedParameter(Expression("foo + 1"), {'foo': ConstantParameter(3)})
p2 = MappedParameter(Expression("foo + 1"), {'foo': ConstantParameter(4)})
p3 = MappedParameter(Expression("foo + 1"), {'foo': ConstantParameter(3)})

self.assertEqual(p1, p3)
self.assertNotEqual(p1, p2)
Expand Down
7 changes: 5 additions & 2 deletions tests/pulses/pulse_template_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ class PulseTemplateTest(unittest.TestCase):

def test_create_program(self) -> None:
template = PulseTemplateStub(defined_channels={'A'}, parameter_names={'foo'})
parameters = {'foo': ConstantParameter(2.126), 'bar': -26.2, 'hugo': 'exp(sin(pi/2))', 'append_a_child': '1'}
parameters = {'foo': 2.126, 'bar': -26.2, 'hugo': 'exp(sin(pi/2))', 'append_a_child': '1'}
previous_parameters = parameters.copy()
measurement_mapping = {'M': 'N'}
previos_measurement_mapping = measurement_mapping.copy()
Expand Down Expand Up @@ -304,7 +304,10 @@ def test_create_program_channel_mapping(self):

def test_create_program_none(self) -> None:
template = PulseTemplateStub(defined_channels={'A'}, parameter_names={'foo'})
parameters = {'foo': ConstantParameter(2.126), 'bar': -26.2, 'hugo': 'exp(sin(pi/2))'}
with self.assertWarns(DeprecationWarning):
# just a test that old stuff wont break. remove in the future
constant_parameter = ConstantParameter(2.126)
parameters = {'foo': constant_parameter, 'bar': -26.2, 'hugo': 'exp(sin(pi/2))'}
measurement_mapping = {'M': 'N'}
channel_mapping = {'A': 'B'}
volatile = {'hugo'}
Expand Down
1 change: 0 additions & 1 deletion tests/pulses/repetition_pulse_template_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,6 @@ def test_create_program_declaration_parameter_not_provided(self) -> None:
global_transformation=None,
parent_loop=program)

parameters = {'foo': ConstantParameter(7)}
with self.assertRaises(ParameterNotProvidedException):
t._internal_create_program(scope=scope,
measurement_mapping=measurement_mapping,
Expand Down
10 changes: 5 additions & 5 deletions tests/pulses/sequence_pulse_template_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from qupulse.pulses.table_pulse_template import TablePulseTemplate
from qupulse.pulses.sequence_pulse_template import SequencePulseTemplate, SequenceWaveform
from qupulse.pulses.mapping_pulse_template import MappingPulseTemplate
from qupulse.pulses.parameters import ConstantParameter, ParameterConstraint, ParameterConstraintViolation, ParameterNotProvidedException
from qupulse.pulses.parameters import ParameterConstraint, ParameterConstraintViolation, ParameterNotProvidedException
from qupulse._program._loop import Loop

from tests.pulses.sequencing_dummies import DummyPulseTemplate,\
Expand Down Expand Up @@ -39,10 +39,10 @@ def __init__(self, *args, **kwargs) -> None:
self.outer_parameters = {'uptime', 'length', 'pulse_length', 'voltage'}

self.parameters = dict()
self.parameters['uptime'] = ConstantParameter(5)
self.parameters['length'] = ConstantParameter(10)
self.parameters['pulse_length'] = ConstantParameter(100)
self.parameters['voltage'] = ConstantParameter(10)
self.parameters['uptime'] = 5
self.parameters['length'] = 10
self.parameters['pulse_length'] = 100
self.parameters['voltage'] = 10

self.sequence = SequencePulseTemplate(MappingPulseTemplate(self.square,
parameter_mapping=self.mapping1,
Expand Down
12 changes: 8 additions & 4 deletions tests/serialization_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,8 @@ def test_get_contents_iter_len(self) -> None:
for name in expected:
self.backend.put(name, self.test_data)

self.assertEqual(expected, self.backend.list_contents(), msg="list_contents() faulty")
with self.assertWarns(DeprecationWarning):
self.assertEqual(expected, self.backend.list_contents(), msg="list_contents() faulty")
self.assertEqual(expected, set(iter(self.backend)), msg="__iter__() faulty")
self.assertEqual(3, len(self.backend), msg="__len__() faulty")

Expand Down Expand Up @@ -527,7 +528,8 @@ def test_get_contents_iter_len(self) -> None:
for name in expected:
self.backend.put(name, "asdfasdfas")

self.assertEqual(expected, self.backend.list_contents(), msg="list_contents() faulty")
with self.assertWarns(DeprecationWarning):
self.assertEqual(expected, self.backend.list_contents(), msg="list_contents() faulty")
self.assertEqual(expected, set(iter(self.backend)), msg="__iter__() faulty")
self.assertEqual(3, len(self.backend), msg="__len__() faulty")

Expand Down Expand Up @@ -629,7 +631,8 @@ def test_get_contents_iter_len(self) -> None:
for name in expected:
self.dummy_backend.put(name, "asdfasdfas")

self.assertEqual(expected, self.caching_backend.list_contents(), msg="list_contents() faulty")
with self.assertWarns(DeprecationWarning):
self.assertEqual(expected, self.caching_backend.list_contents(), msg="list_contents() faulty")
self.assertEqual(expected, set(iter(self.caching_backend)), msg="__iter__() faulty")
self.assertEqual(3, len(self.caching_backend), msg="__len__() faulty")

Expand Down Expand Up @@ -678,7 +681,8 @@ def test_get_contents_iter_len(self) -> None:
for name in expected:
self.backend.put(name, "asdfasdfas")

self.assertEqual(expected, self.backend.list_contents(), msg="list_contents() faulty")
with self.assertWarns(DeprecationWarning):
self.assertEqual(expected, self.backend.list_contents(), msg="list_contents() faulty")
self.assertEqual(expected, set(iter(self.backend)), msg="__iter__() faulty")
self.assertEqual(3, len(self.backend), msg="__len__() faulty")

Expand Down

0 comments on commit 78be892

Please sign in to comment.