Skip to content

Commit

Permalink
Merge pull request #2271 from jenshnielsen/fix_sorted_validator
Browse files Browse the repository at this point in the history
Fix sequnce validator for with sorted = True
  • Loading branch information
jenshnielsen committed Oct 12, 2020
2 parents 899f93c + 0052e1f commit 53bbf08
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
62 changes: 62 additions & 0 deletions qcodes/tests/validators/test_sequence.py
@@ -0,0 +1,62 @@
import pytest
from qcodes.utils.validators import Ints, Sequence


def test_type():
l = Sequence()
v1 = ['a', 'b', 5]
l.validate(v1)

l.validate((1, 2, 3))

v2 = 234
with pytest.raises(TypeError):
l.validate(v2)


def test_elt_vals():
l = Sequence(Ints(max_value=10))
v1 = [0, 1, 5]
l.validate(v1)

v2 = [0, 1, 11]
with pytest.raises(ValueError, match="11 is invalid: must be between"):
l.validate(v2)


def test_valid_values():
val = Sequence(Ints(max_value=10))
for vval in val.valid_values:
val.validate(vval)


def test_length():
l = Sequence(length=3)
v1 = [0, 1, 5]
l.validate(v1)

v2 = [0, 1, 3, 4]
with pytest.raises(ValueError, match="has not length"):
l.validate(v2)

v3 = [3, 4]
with pytest.raises(ValueError, match="has not length"):
l.validate(v3)


def test_sorted():
l = Sequence(length=3, require_sorted=True)

v1 = [0, 1, 5]
l.validate(v1)

v2 = (1, 3, 5)
l.validate(v2)

v3 = (1, 5, 3)
with pytest.raises(ValueError, match="is required to be sorted"):
l.validate(v3)

v4 = [1, 7, 2]
with pytest.raises(ValueError, match="is required to be sorted"):
l.validate(v4)
2 changes: 1 addition & 1 deletion qcodes/utils/validators.py
Expand Up @@ -895,7 +895,7 @@ def validate(self, value: collections.abc.Sequence,
if self._length and not len(value) == self._length:
raise ValueError(
f'{repr(value)} has not length {self._length} but {len(value)}')
if self._require_sorted and sorted(value) != value:
if self._require_sorted and tuple(sorted(value)) != tuple(value):
raise ValueError(
f'{repr(value)} is required to be sorted.')
# Does not validate elements if not required to improve performance
Expand Down

0 comments on commit 53bbf08

Please sign in to comment.