Skip to content

Commit 0b5d508

Browse files
committed
Add tests for SciType validators
1 parent ba38110 commit 0b5d508

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

traittypes/tests/test_validators.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#!/usr/bin/env python
2+
# coding: utf-8
3+
4+
# Copyright (c) Jupyter Development Team.
5+
# Distributed under the terms of the Modified BSD License.
6+
7+
import pytest
8+
9+
from traitlets import HasTraits, TraitError
10+
11+
from ..traittypes import SciType
12+
13+
14+
def test_coercion_validator():
15+
# Test with a squeeze coercion
16+
def truncate(trait, value):
17+
return value[:10]
18+
19+
class Foo(HasTraits):
20+
bar = SciType().valid(truncate)
21+
22+
foo = Foo(bar=list(range(20)))
23+
assert foo.bar == list(range(10))
24+
foo.bar = list(range(10, 40))
25+
assert foo.bar == list(range(10, 20))
26+
27+
28+
def test_validaton_error():
29+
# Test with a squeeze coercion
30+
def maxlen(trait, value):
31+
if len(value) > 10:
32+
raise ValueError('Too long sequence!')
33+
return value
34+
35+
class Foo(HasTraits):
36+
bar = SciType().valid(maxlen)
37+
38+
# Check that it works as expected:
39+
foo = Foo(bar=list(range(5)))
40+
assert foo.bar == list(range(5))
41+
# Check that it fails as expected:
42+
with pytest.raises(TraitError): # Should convert ValueError to TraitError
43+
foo.bar = list(range(10, 40))
44+
assert foo.bar == list(range(5))
45+
# Check that it can again be set correctly
46+
foo = Foo(bar=list(range(5, 10)))
47+
assert foo.bar == list(range(5, 10))

0 commit comments

Comments
 (0)