File: test_trait_types.py

package info (click to toggle)
python-traits 6.4.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 8,648 kB
  • sloc: python: 34,801; ansic: 4,266; makefile: 102
file content (173 lines) | stat: -rw-r--r-- 5,582 bytes parent folder | download
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# (C) Copyright 2005-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!

""" Unit test case for testing trait types created by subclassing TraitType.
"""

import os
import sys
import tempfile
import textwrap
import shutil
import subprocess
import unittest

from traits.api import (
    DefaultValue,
    Float,
    Function,
    Method,
    NoDefaultSpecified,
    Symbol,
    TraitType,
    Undefined
)
from traits.testing.optional_dependencies import requires_numpy


class TraitTypesTest(unittest.TestCase):
    def test_traits_shared_transient(self):
        # Regression test for a bug in traits where the same _metadata
        # dictionary was shared between different trait types.
        class LazyProperty(TraitType):

            #: The default value type to use.
            default_value_type = DefaultValue.constant

            def get(self, obj, name):
                return 1729

        self.assertFalse(Float().transient)
        LazyProperty().as_ctrait()
        self.assertFalse(Float().transient)

    @requires_numpy
    def test_numpy_validators_loaded_if_numpy_present(self):
        # If 'numpy' is available, the numpy validators should be loaded,
        # even if numpy is imported after traits.
        test_script = textwrap.dedent("""
            from traits.trait_types import bool_fast_validate
            import numpy

            if numpy.bool_ in bool_fast_validate:
                print("Success")
            else:
                print("Failure")
        """)
        this_python = sys.executable
        tmpdir = tempfile.mkdtemp()
        try:
            tmpfile = os.path.join(tmpdir, "test_script.py")
            with open(tmpfile, "w", encoding="utf-8") as f:
                f.write(test_script)
            cmd = [this_python, tmpfile]
            output = subprocess.check_output(cmd).decode("utf-8")
        finally:
            shutil.rmtree(tmpdir)

        self.assertEqual(output.strip(), "Success")

    def test_default_value_in_init(self):

        class MyTraitType(TraitType):
            pass

        # Tests for the behaviour of the default_value argument
        # to TraitType.__init__.
        trait_type = MyTraitType(default_value=23)
        self.assertEqual(
            trait_type.get_default_value(),
            (DefaultValue.constant, 23),
        )

        # An explicit default value of None should work as expected.
        trait_type = MyTraitType(default_value=None)
        self.assertEqual(
            trait_type.get_default_value(),
            (DefaultValue.constant, None),
        )

        # If no default is given, get_default_value() returns a value
        # of Undefined.
        trait_type = MyTraitType()
        self.assertEqual(
            trait_type.get_default_value(),
            (DefaultValue.constant, Undefined),
        )

        # Similarly, if NoDefaultSpecified is given, get_default_value()
        # is Undefined.
        trait_type = MyTraitType(default_value=NoDefaultSpecified)
        self.assertEqual(
            trait_type.get_default_value(),
            (DefaultValue.constant, Undefined),
        )

    def test_disallowed_default_value(self):
        class MyTraitType(TraitType):

            default_value_type = DefaultValue.disallow

        trait_type = MyTraitType()
        self.assertEqual(
            trait_type.get_default_value(),
            (DefaultValue.disallow, Undefined)
        )

        ctrait = trait_type.as_ctrait()
        self.assertEqual(
            ctrait.default_value(),
            (DefaultValue.disallow, Undefined),
        )
        self.assertEqual(ctrait.default_kind, "invalid")
        self.assertEqual(ctrait.default, Undefined)

        with self.assertRaises(ValueError):
            ctrait.default_value_for(None, "<dummy>")

    def test_call_sets_default_value_type(self):
        class FooTrait(TraitType):
            default_value_type = DefaultValue.callable_and_args

            def __init__(self, default_value=NoDefaultSpecified, **metadata):
                default_value = (pow, (3, 4), {})
                super().__init__(default_value, **metadata)

        trait = FooTrait()
        ctrait = trait.as_ctrait()
        self.assertEqual(ctrait.default_value_for(None, "dummy"), 81)
        cloned_ctrait = trait(30)
        self.assertEqual(cloned_ctrait.default_value_for(None, "dummy"), 30)


class TestDeprecatedTraitTypes(unittest.TestCase):
    def test_function_deprecated(self):
        def some_function():
            pass

        with self.assertWarnsRegex(DeprecationWarning, "Function trait type"):
            Function()
        with self.assertWarnsRegex(DeprecationWarning, "Function trait type"):
            Function(some_function, washable=True)

    def test_method_deprecated(self):

        class A:
            def some_method(self):
                pass

        with self.assertWarnsRegex(DeprecationWarning, "Method trait type"):
            Method()
        with self.assertWarnsRegex(DeprecationWarning, "Method trait type"):
            Method(A().some_method, gluten_free=False)

    def test_symbol_deprecated(self):
        with self.assertWarnsRegex(DeprecationWarning, "Symbol trait type"):
            Symbol("random:random")