File: test_validators.py

package info (click to toggle)
traittypes 0.2.1-4
  • links: PTS
  • area: main
  • in suites: bookworm
  • size: 172 kB
  • sloc: python: 514; makefile: 161
file content (47 lines) | stat: -rw-r--r-- 1,267 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#!/usr/bin/env python
# coding: utf-8

# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.

import pytest

from traitlets import HasTraits, TraitError

from ..traittypes import SciType


def test_coercion_validator():
    # Test with a squeeze coercion
    def truncate(trait, value):
        return value[:10]

    class Foo(HasTraits):
        bar = SciType().valid(truncate)

    foo = Foo(bar=list(range(20)))
    assert foo.bar == list(range(10))
    foo.bar = list(range(10, 40))
    assert foo.bar == list(range(10, 20))


def test_validaton_error():
    # Test with a squeeze coercion
    def maxlen(trait, value):
        if len(value) > 10:
            raise ValueError('Too long sequence!')
        return value

    class Foo(HasTraits):
        bar = SciType().valid(maxlen)

    # Check that it works as expected:
    foo = Foo(bar=list(range(5)))
    assert foo.bar == list(range(5))
    # Check that it fails as expected:
    with pytest.raises(TraitError):  # Should convert ValueError to TraitError
        foo.bar = list(range(10, 40))
    assert foo.bar == list(range(5))
    # Check that it can again be set correctly
    foo = Foo(bar=list(range(5, 10)))
    assert foo.bar == list(range(5, 10))