Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleaning up all warnings during tests #471

Merged
merged 6 commits into from
Mar 1, 2023
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions pulser-core/pulser/parametrized/paramobj.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,8 +303,8 @@ def __call__(self, *args: Any, **kwargs: Any) -> ParamObj:
def __getattr__(self, name: str) -> ParamObj:
if hasattr(self.cls, name):
warnings.warn(
"Serialization of 'getattr' calls to parametrized "
"objects is not supported, so this object can't be serialied.",
"Serialization of 'getattr' calls to parametrized objects "
"is not supported, so this object can't be serialized.",
stacklevel=2,
)
return ParamObj(getattr, self, name)
Expand Down
8 changes: 8 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,11 @@ line-length = 79
profile = "black"
line_length = 79
src_paths = ["pulser-core", "pulser-simulation", "pulser-pasqal"]

[tool.pytest.ini_options]
filterwarnings = [
# All warnings are turned into errors
"error",
# Except this particular warnings, which is ignored
'ignore:A duration of \d+ ns is not a multiple of:UserWarning',
]
28 changes: 22 additions & 6 deletions tests/test_abstract_repr.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,9 @@ def test_values(self, abstract):

def test_exceptions(self, sequence):
with pytest.raises(TypeError, match="not JSON serializable"):
Sequence(Register3D.cubic(2), MockDevice).to_abstract_repr()
Sequence(
Register3D.cubic(2, prefix="q"), MockDevice
).to_abstract_repr()

with pytest.raises(
ValueError, match="No signature found for 'FakeWaveform'"
Expand All @@ -274,7 +276,9 @@ def test_exceptions(self, sequence):
with pytest.raises(ValueError, match="'foo' is not in the signature"):
abstract_repr("ConstantWaveform", 1000, 1, foo=0)

with pytest.raises(
with pytest.warns(
UserWarning, match="converts all qubit ID's to strings"
), pytest.raises(
AbstractReprError, match="Name collisions encountered"
):
Register({"0": (0, 0), 0: (20, 20)})._to_abstract_repr()
Expand Down Expand Up @@ -338,6 +342,9 @@ def test_abstract_repr_encoder(self, obj, serialized_obj):
serialized_obj
)

@pytest.mark.filterwarnings(
"ignore:Serialization of 'getattr':UserWarning"
)
def test_paramobj_serialization(self, sequence):
var = sequence._variables["duration"][0]
ser_var = {
Expand All @@ -347,10 +354,16 @@ def test_paramobj_serialization(self, sequence):
}
wf = BlackmanWaveform(1000, 1.0)
ser_wf = wf._to_abstract_repr()
with pytest.raises(
ValueError, match="Serialization of calls to parametrized objects"
):
warn_msg = (
"Calls to methods of parametrized objects are only "
"executed if they serve as arguments of other parametrized"
" objects that are themselves built"
)
with pytest.warns(UserWarning, match=warn_msg):
param_obj_call = BlackmanWaveform(var, 1)()

err_msg = "Serialization of calls to parametrized objects"
with pytest.raises(ValueError, match=err_msg):
json.dumps(param_obj_call, cls=AbstractReprEncoder)

s = json.dumps(
Expand Down Expand Up @@ -718,7 +731,10 @@ def test_deserialize_variables(self, without_default):
"zou": {"type": "float", "value": [3.14]},
}
)
_check_roundtrip(s)
with pytest.warns(
UserWarning, match="Building a non-parametrized sequence"
):
_check_roundtrip(s)
seq = Sequence.from_abstract_repr(json.dumps(s))
if without_default:
# Serialize and deserialize again, without the defaults
Expand Down
4 changes: 3 additions & 1 deletion tests/test_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,9 @@ def test_rare_cases():
var = seq.declare_variable("var")

wf = BlackmanWaveform(var * 100 // 10, var)
with pytest.raises(
with pytest.warns(
UserWarning, match="Serialization of 'getattr'"
), pytest.raises(
ValueError, match="Serialization of calls to parametrized objects"
):
s = encode(wf.draw())
Expand Down
5 changes: 3 additions & 2 deletions tests/test_parametrized.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,8 +97,9 @@ def test_paramobj():
assert str(pulse2) == f"Pulse({str(bwf)}, {str(bwf)}, 1)"
with pytest.raises(AttributeError):
bwf._duration
time = bwf.duration
samps = bwf.samples
with pytest.warns(UserWarning, match="Serialization of 'getattr'"):
time = bwf.duration
samps = bwf.samples
cwf = CompositeWaveform(bwf, bwf)
t._assign(1000)
a._assign(np.pi)
Expand Down
19 changes: 11 additions & 8 deletions tests/test_pasqal.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,11 @@ def check_pasqal_cloud(fixt, seq, device_type, expected_seq_representation):
"jobs": [{"runs": 10, "variables": {"qubits": None, "a": [3, 5]}}],
}

fixt.pasqal_cloud.create_batch(
seq,
**create_batch_kwargs,
)
with pytest.warns(UserWarning, match="No declared variables named: a"):
fixt.pasqal_cloud.create_batch(
seq,
**create_batch_kwargs,
)

fixt.mock_cloud_sdk.create_batch.assert_called_once_with(
serialized_sequence=expected_seq_representation,
Expand All @@ -116,7 +117,9 @@ def check_pasqal_cloud(fixt, seq, device_type, expected_seq_representation):
],
)
def test_pasqal_cloud_emu(fixt, device_type, device):
reg = Register(dict(enumerate([(0, 0), (0, 10)])))
reg = Register.from_coordinates(
[(0, 0), (0, 10)], center=False, prefix="q"
)
seq = Sequence(reg, device)

check_pasqal_cloud(
Expand Down Expand Up @@ -166,9 +169,9 @@ def test_wrong_parameters(fixt):
seq = Sequence(reg, test_device)
seq.declare_variable("unset", dtype=int)

with pytest.raises(
TypeError, match="Did not receive values for variables"
):
with pytest.warns(
UserWarning, match="No declared variables named: a"
), pytest.raises(TypeError, match="Did not receive values for variables"):
fixt.pasqal_cloud.create_batch(
seq,
jobs=[JobParameters(runs=10, variables=JobVariables(a=[3, 5]))],
Expand Down
9 changes: 8 additions & 1 deletion tests/test_register_layout.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
# See the License for the specific language governing permissions and
# limitations under the License.

import contextlib
import re
from hashlib import sha256
from unittest.mock import patch
Expand All @@ -38,7 +39,13 @@ def layout3d():


def test_creation(layout, layout3d):
with pytest.raises(
np_version = tuple(map(int, np.__version__.split(".")))
context_manager = (
pytest.warns(np.VisibleDeprecationWarning)
if np_version < (1, 22)
else contextlib.nullcontext()
)
with context_manager, pytest.raises(
ValueError, match="must be an array or list of coordinates"
):
RegisterLayout([[0, 0, 0], [1, 1], [1, 0], [0, 1]])
Expand Down
24 changes: 20 additions & 4 deletions tests/test_sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from typing import Any
from unittest.mock import patch

import matplotlib.pyplot as plt
import numpy as np
import pytest

Expand Down Expand Up @@ -357,7 +358,12 @@ def test_switch_device_down(devices, pulses):
def test_switch_device_up(device_ind, devices, pulses, strict):
# Device checkout
seq = init_seq(Chadoq2, "ising", "rydberg_global", None)
assert seq.switch_device(Chadoq2)._device == Chadoq2
with pytest.warns(
UserWarning,
match="Switching a sequence to the same device returns the "
"sequence unchanged",
):
assert seq.switch_device(Chadoq2)._device == Chadoq2

# Test non-strict mode
assert "ising" in seq.switch_device(devices[0]).declared_channels
Expand Down Expand Up @@ -411,7 +417,11 @@ def test_switch_device_eom():
assert seq._schedule["rydberg"].eom_blocks

err_base = "No match for channel rydberg "
with pytest.raises(
warns_msg = (
"Switching to a device with a different Rydberg level,"
" check that the expected Rydberg interactions still hold."
)
with pytest.warns(UserWarning, match=warns_msg), pytest.raises(
TypeError, match=err_base + "with an EOM configuration."
):
seq.switch_device(Chadoq2)
Expand Down Expand Up @@ -681,6 +691,7 @@ def test_sequence():
with patch("matplotlib.figure.Figure.savefig"):
seq.draw(fig_name="my_sequence.pdf")
seq.draw(draw_register=True, fig_name="both.pdf")
plt.close()

pulse1 = Pulse(
InterpolatedWaveform(500, [0, 1, 0]),
Expand Down Expand Up @@ -750,17 +761,19 @@ def test_sequence():

with patch("matplotlib.pyplot.show"):
seq.draw(draw_phase_shifts=True)
plt.close()

assert seq.get_duration() == 4000

seq.measure(basis="digital")

with patch("matplotlib.pyplot.show"):
seq.draw(draw_phase_area=True)
plt.close()

with patch("matplotlib.pyplot.show"):
seq.draw(draw_phase_curve=True)

plt.close()
s = seq.serialize()
assert json.loads(s)["__version__"] == pulser.__version__
seq_ = Sequence.deserialize(s)
Expand Down Expand Up @@ -891,6 +904,7 @@ def test_slm_mask():
# Check drawing method
with patch("matplotlib.pyplot.show"):
seq_xy2.draw()
plt.close()


def test_draw_register():
Expand All @@ -904,7 +918,7 @@ def test_draw_register():
seq.config_slm_mask(targets)
with patch("matplotlib.pyplot.show"):
seq.draw(draw_register=True)

plt.close()
# Draw 3d register from sequence
reg3d = Register3D.cubic(3, 8)
seq3d = Sequence(reg3d, MockDevice)
Expand All @@ -914,6 +928,7 @@ def test_draw_register():
seq3d.measure(basis="XY")
with patch("matplotlib.pyplot.show"):
seq3d.draw(draw_register=True)
plt.close()


def test_hardware_constraints():
Expand Down Expand Up @@ -1020,6 +1035,7 @@ def test_hardware_constraints():
):
seq.draw(mode="output")
seq.draw(mode="input+output")
plt.close()


def test_mappable_register():
Expand Down
3 changes: 2 additions & 1 deletion tests/test_simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,8 @@ def test_initialization_and_construction_of_hamiltonian(seq):
assert sh == sim.dim**sim._size

assert not seq.is_parametrized()
seq_copy = seq.build() # Take a copy of the sequence
with pytest.warns(UserWarning, match="returns a copy of itself"):
seq_copy = seq.build() # Take a copy of the sequence
x = seq_copy.declare_variable("x")
seq_copy.add(Pulse.ConstantPulse(x, 1, 0, 0), "ryd")
assert seq_copy.is_parametrized()
Expand Down