##// END OF EJS Templates
Fix more cases relying on dict ordering in utils
Thomas Kluyver -
Show More
@@ -1,94 +1,94 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Utilities for working with stack frames.
3 Utilities for working with stack frames.
4 """
4 """
5
5
6 #-----------------------------------------------------------------------------
6 #-----------------------------------------------------------------------------
7 # Copyright (C) 2008-2011 The IPython Development Team
7 # Copyright (C) 2008-2011 The IPython Development Team
8 #
8 #
9 # Distributed under the terms of the BSD License. The full license is in
9 # Distributed under the terms of the BSD License. The full license is in
10 # the file COPYING, distributed as part of this software.
10 # the file COPYING, distributed as part of this software.
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 import sys
17 import sys
18 from IPython.utils import py3compat
18 from IPython.utils import py3compat
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Code
21 # Code
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 @py3compat.doctest_refactor_print
24 @py3compat.doctest_refactor_print
25 def extract_vars(*names,**kw):
25 def extract_vars(*names,**kw):
26 """Extract a set of variables by name from another frame.
26 """Extract a set of variables by name from another frame.
27
27
28 :Parameters:
28 :Parameters:
29 - `*names`: strings
29 - `*names`: strings
30 One or more variable names which will be extracted from the caller's
30 One or more variable names which will be extracted from the caller's
31 frame.
31 frame.
32
32
33 :Keywords:
33 :Keywords:
34 - `depth`: integer (0)
34 - `depth`: integer (0)
35 How many frames in the stack to walk when looking for your variables.
35 How many frames in the stack to walk when looking for your variables.
36
36
37
37
38 Examples:
38 Examples:
39
39
40 In [2]: def func(x):
40 In [2]: def func(x):
41 ...: y = 1
41 ...: y = 1
42 ...: print extract_vars('x','y')
42 ...: print sorted(extract_vars('x','y').items())
43 ...:
43 ...:
44
44
45 In [3]: func('hello')
45 In [3]: func('hello')
46 {'y': 1, 'x': 'hello'}
46 [('x', 'hello'), ('y', 1)]
47 """
47 """
48
48
49 depth = kw.get('depth',0)
49 depth = kw.get('depth',0)
50
50
51 callerNS = sys._getframe(depth+1).f_locals
51 callerNS = sys._getframe(depth+1).f_locals
52 return dict((k,callerNS[k]) for k in names)
52 return dict((k,callerNS[k]) for k in names)
53
53
54
54
55 def extract_vars_above(*names):
55 def extract_vars_above(*names):
56 """Extract a set of variables by name from another frame.
56 """Extract a set of variables by name from another frame.
57
57
58 Similar to extractVars(), but with a specified depth of 1, so that names
58 Similar to extractVars(), but with a specified depth of 1, so that names
59 are exctracted exactly from above the caller.
59 are exctracted exactly from above the caller.
60
60
61 This is simply a convenience function so that the very common case (for us)
61 This is simply a convenience function so that the very common case (for us)
62 of skipping exactly 1 frame doesn't have to construct a special dict for
62 of skipping exactly 1 frame doesn't have to construct a special dict for
63 keyword passing."""
63 keyword passing."""
64
64
65 callerNS = sys._getframe(2).f_locals
65 callerNS = sys._getframe(2).f_locals
66 return dict((k,callerNS[k]) for k in names)
66 return dict((k,callerNS[k]) for k in names)
67
67
68
68
69 def debugx(expr,pre_msg=''):
69 def debugx(expr,pre_msg=''):
70 """Print the value of an expression from the caller's frame.
70 """Print the value of an expression from the caller's frame.
71
71
72 Takes an expression, evaluates it in the caller's frame and prints both
72 Takes an expression, evaluates it in the caller's frame and prints both
73 the given expression and the resulting value (as well as a debug mark
73 the given expression and the resulting value (as well as a debug mark
74 indicating the name of the calling function. The input must be of a form
74 indicating the name of the calling function. The input must be of a form
75 suitable for eval().
75 suitable for eval().
76
76
77 An optional message can be passed, which will be prepended to the printed
77 An optional message can be passed, which will be prepended to the printed
78 expr->value pair."""
78 expr->value pair."""
79
79
80 cf = sys._getframe(1)
80 cf = sys._getframe(1)
81 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
81 print '[DBG:%s] %s%s -> %r' % (cf.f_code.co_name,pre_msg,expr,
82 eval(expr,cf.f_globals,cf.f_locals))
82 eval(expr,cf.f_globals,cf.f_locals))
83
83
84
84
85 # deactivate it by uncommenting the following line, which makes it a no-op
85 # deactivate it by uncommenting the following line, which makes it a no-op
86 #def debugx(expr,pre_msg=''): pass
86 #def debugx(expr,pre_msg=''): pass
87
87
88 def extract_module_locals(depth=0):
88 def extract_module_locals(depth=0):
89 """Returns (module, locals) of the funciton `depth` frames away from the caller"""
89 """Returns (module, locals) of the funciton `depth` frames away from the caller"""
90 f = sys._getframe(depth + 1)
90 f = sys._getframe(depth + 1)
91 global_ns = f.f_globals
91 global_ns = f.f_globals
92 module = sys.modules[global_ns['__name__']]
92 module = sys.modules[global_ns['__name__']]
93 return (module, f.f_locals)
93 return (module, f.f_locals)
94
94
@@ -1,908 +1,908 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Tests for IPython.utils.traitlets.
3 Tests for IPython.utils.traitlets.
4
4
5 Authors:
5 Authors:
6
6
7 * Brian Granger
7 * Brian Granger
8 * Enthought, Inc. Some of the code in this file comes from enthought.traits
8 * Enthought, Inc. Some of the code in this file comes from enthought.traits
9 and is licensed under the BSD license. Also, many of the ideas also come
9 and is licensed under the BSD license. Also, many of the ideas also come
10 from enthought.traits even though our implementation is very different.
10 from enthought.traits even though our implementation is very different.
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Copyright (C) 2008-2011 The IPython Development Team
14 # Copyright (C) 2008-2011 The IPython Development Team
15 #
15 #
16 # Distributed under the terms of the BSD License. The full license is in
16 # Distributed under the terms of the BSD License. The full license is in
17 # the file COPYING, distributed as part of this software.
17 # the file COPYING, distributed as part of this software.
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Imports
21 # Imports
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 import re
24 import re
25 import sys
25 import sys
26 from unittest import TestCase
26 from unittest import TestCase
27
27
28 from nose import SkipTest
28 from nose import SkipTest
29
29
30 from IPython.utils.traitlets import (
30 from IPython.utils.traitlets import (
31 HasTraits, MetaHasTraits, TraitType, Any, CBytes,
31 HasTraits, MetaHasTraits, TraitType, Any, CBytes,
32 Int, Long, Integer, Float, Complex, Bytes, Unicode, TraitError,
32 Int, Long, Integer, Float, Complex, Bytes, Unicode, TraitError,
33 Undefined, Type, This, Instance, TCPAddress, List, Tuple,
33 Undefined, Type, This, Instance, TCPAddress, List, Tuple,
34 ObjectName, DottedObjectName, CRegExp
34 ObjectName, DottedObjectName, CRegExp
35 )
35 )
36 from IPython.utils import py3compat
36 from IPython.utils import py3compat
37 from IPython.testing.decorators import skipif
37 from IPython.testing.decorators import skipif
38
38
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40 # Helper classes for testing
40 # Helper classes for testing
41 #-----------------------------------------------------------------------------
41 #-----------------------------------------------------------------------------
42
42
43
43
44 class HasTraitsStub(HasTraits):
44 class HasTraitsStub(HasTraits):
45
45
46 def _notify_trait(self, name, old, new):
46 def _notify_trait(self, name, old, new):
47 self._notify_name = name
47 self._notify_name = name
48 self._notify_old = old
48 self._notify_old = old
49 self._notify_new = new
49 self._notify_new = new
50
50
51
51
52 #-----------------------------------------------------------------------------
52 #-----------------------------------------------------------------------------
53 # Test classes
53 # Test classes
54 #-----------------------------------------------------------------------------
54 #-----------------------------------------------------------------------------
55
55
56
56
57 class TestTraitType(TestCase):
57 class TestTraitType(TestCase):
58
58
59 def test_get_undefined(self):
59 def test_get_undefined(self):
60 class A(HasTraits):
60 class A(HasTraits):
61 a = TraitType
61 a = TraitType
62 a = A()
62 a = A()
63 self.assertEquals(a.a, Undefined)
63 self.assertEquals(a.a, Undefined)
64
64
65 def test_set(self):
65 def test_set(self):
66 class A(HasTraitsStub):
66 class A(HasTraitsStub):
67 a = TraitType
67 a = TraitType
68
68
69 a = A()
69 a = A()
70 a.a = 10
70 a.a = 10
71 self.assertEquals(a.a, 10)
71 self.assertEquals(a.a, 10)
72 self.assertEquals(a._notify_name, 'a')
72 self.assertEquals(a._notify_name, 'a')
73 self.assertEquals(a._notify_old, Undefined)
73 self.assertEquals(a._notify_old, Undefined)
74 self.assertEquals(a._notify_new, 10)
74 self.assertEquals(a._notify_new, 10)
75
75
76 def test_validate(self):
76 def test_validate(self):
77 class MyTT(TraitType):
77 class MyTT(TraitType):
78 def validate(self, inst, value):
78 def validate(self, inst, value):
79 return -1
79 return -1
80 class A(HasTraitsStub):
80 class A(HasTraitsStub):
81 tt = MyTT
81 tt = MyTT
82
82
83 a = A()
83 a = A()
84 a.tt = 10
84 a.tt = 10
85 self.assertEquals(a.tt, -1)
85 self.assertEquals(a.tt, -1)
86
86
87 def test_default_validate(self):
87 def test_default_validate(self):
88 class MyIntTT(TraitType):
88 class MyIntTT(TraitType):
89 def validate(self, obj, value):
89 def validate(self, obj, value):
90 if isinstance(value, int):
90 if isinstance(value, int):
91 return value
91 return value
92 self.error(obj, value)
92 self.error(obj, value)
93 class A(HasTraits):
93 class A(HasTraits):
94 tt = MyIntTT(10)
94 tt = MyIntTT(10)
95 a = A()
95 a = A()
96 self.assertEquals(a.tt, 10)
96 self.assertEquals(a.tt, 10)
97
97
98 # Defaults are validated when the HasTraits is instantiated
98 # Defaults are validated when the HasTraits is instantiated
99 class B(HasTraits):
99 class B(HasTraits):
100 tt = MyIntTT('bad default')
100 tt = MyIntTT('bad default')
101 self.assertRaises(TraitError, B)
101 self.assertRaises(TraitError, B)
102
102
103 def test_is_valid_for(self):
103 def test_is_valid_for(self):
104 class MyTT(TraitType):
104 class MyTT(TraitType):
105 def is_valid_for(self, value):
105 def is_valid_for(self, value):
106 return True
106 return True
107 class A(HasTraits):
107 class A(HasTraits):
108 tt = MyTT
108 tt = MyTT
109
109
110 a = A()
110 a = A()
111 a.tt = 10
111 a.tt = 10
112 self.assertEquals(a.tt, 10)
112 self.assertEquals(a.tt, 10)
113
113
114 def test_value_for(self):
114 def test_value_for(self):
115 class MyTT(TraitType):
115 class MyTT(TraitType):
116 def value_for(self, value):
116 def value_for(self, value):
117 return 20
117 return 20
118 class A(HasTraits):
118 class A(HasTraits):
119 tt = MyTT
119 tt = MyTT
120
120
121 a = A()
121 a = A()
122 a.tt = 10
122 a.tt = 10
123 self.assertEquals(a.tt, 20)
123 self.assertEquals(a.tt, 20)
124
124
125 def test_info(self):
125 def test_info(self):
126 class A(HasTraits):
126 class A(HasTraits):
127 tt = TraitType
127 tt = TraitType
128 a = A()
128 a = A()
129 self.assertEquals(A.tt.info(), 'any value')
129 self.assertEquals(A.tt.info(), 'any value')
130
130
131 def test_error(self):
131 def test_error(self):
132 class A(HasTraits):
132 class A(HasTraits):
133 tt = TraitType
133 tt = TraitType
134 a = A()
134 a = A()
135 self.assertRaises(TraitError, A.tt.error, a, 10)
135 self.assertRaises(TraitError, A.tt.error, a, 10)
136
136
137 def test_dynamic_initializer(self):
137 def test_dynamic_initializer(self):
138 class A(HasTraits):
138 class A(HasTraits):
139 x = Int(10)
139 x = Int(10)
140 def _x_default(self):
140 def _x_default(self):
141 return 11
141 return 11
142 class B(A):
142 class B(A):
143 x = Int(20)
143 x = Int(20)
144 class C(A):
144 class C(A):
145 def _x_default(self):
145 def _x_default(self):
146 return 21
146 return 21
147
147
148 a = A()
148 a = A()
149 self.assertEquals(a._trait_values, {})
149 self.assertEquals(a._trait_values, {})
150 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
150 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
151 self.assertEquals(a.x, 11)
151 self.assertEquals(a.x, 11)
152 self.assertEquals(a._trait_values, {'x': 11})
152 self.assertEquals(a._trait_values, {'x': 11})
153 b = B()
153 b = B()
154 self.assertEquals(b._trait_values, {'x': 20})
154 self.assertEquals(b._trait_values, {'x': 20})
155 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
155 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
156 self.assertEquals(b.x, 20)
156 self.assertEquals(b.x, 20)
157 c = C()
157 c = C()
158 self.assertEquals(c._trait_values, {})
158 self.assertEquals(c._trait_values, {})
159 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
159 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
160 self.assertEquals(c.x, 21)
160 self.assertEquals(c.x, 21)
161 self.assertEquals(c._trait_values, {'x': 21})
161 self.assertEquals(c._trait_values, {'x': 21})
162 # Ensure that the base class remains unmolested when the _default
162 # Ensure that the base class remains unmolested when the _default
163 # initializer gets overridden in a subclass.
163 # initializer gets overridden in a subclass.
164 a = A()
164 a = A()
165 c = C()
165 c = C()
166 self.assertEquals(a._trait_values, {})
166 self.assertEquals(a._trait_values, {})
167 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
167 self.assertEquals(a._trait_dyn_inits.keys(), ['x'])
168 self.assertEquals(a.x, 11)
168 self.assertEquals(a.x, 11)
169 self.assertEquals(a._trait_values, {'x': 11})
169 self.assertEquals(a._trait_values, {'x': 11})
170
170
171
171
172
172
173 class TestHasTraitsMeta(TestCase):
173 class TestHasTraitsMeta(TestCase):
174
174
175 def test_metaclass(self):
175 def test_metaclass(self):
176 self.assertEquals(type(HasTraits), MetaHasTraits)
176 self.assertEquals(type(HasTraits), MetaHasTraits)
177
177
178 class A(HasTraits):
178 class A(HasTraits):
179 a = Int
179 a = Int
180
180
181 a = A()
181 a = A()
182 self.assertEquals(type(a.__class__), MetaHasTraits)
182 self.assertEquals(type(a.__class__), MetaHasTraits)
183 self.assertEquals(a.a,0)
183 self.assertEquals(a.a,0)
184 a.a = 10
184 a.a = 10
185 self.assertEquals(a.a,10)
185 self.assertEquals(a.a,10)
186
186
187 class B(HasTraits):
187 class B(HasTraits):
188 b = Int()
188 b = Int()
189
189
190 b = B()
190 b = B()
191 self.assertEquals(b.b,0)
191 self.assertEquals(b.b,0)
192 b.b = 10
192 b.b = 10
193 self.assertEquals(b.b,10)
193 self.assertEquals(b.b,10)
194
194
195 class C(HasTraits):
195 class C(HasTraits):
196 c = Int(30)
196 c = Int(30)
197
197
198 c = C()
198 c = C()
199 self.assertEquals(c.c,30)
199 self.assertEquals(c.c,30)
200 c.c = 10
200 c.c = 10
201 self.assertEquals(c.c,10)
201 self.assertEquals(c.c,10)
202
202
203 def test_this_class(self):
203 def test_this_class(self):
204 class A(HasTraits):
204 class A(HasTraits):
205 t = This()
205 t = This()
206 tt = This()
206 tt = This()
207 class B(A):
207 class B(A):
208 tt = This()
208 tt = This()
209 ttt = This()
209 ttt = This()
210 self.assertEquals(A.t.this_class, A)
210 self.assertEquals(A.t.this_class, A)
211 self.assertEquals(B.t.this_class, A)
211 self.assertEquals(B.t.this_class, A)
212 self.assertEquals(B.tt.this_class, B)
212 self.assertEquals(B.tt.this_class, B)
213 self.assertEquals(B.ttt.this_class, B)
213 self.assertEquals(B.ttt.this_class, B)
214
214
215 class TestHasTraitsNotify(TestCase):
215 class TestHasTraitsNotify(TestCase):
216
216
217 def setUp(self):
217 def setUp(self):
218 self._notify1 = []
218 self._notify1 = []
219 self._notify2 = []
219 self._notify2 = []
220
220
221 def notify1(self, name, old, new):
221 def notify1(self, name, old, new):
222 self._notify1.append((name, old, new))
222 self._notify1.append((name, old, new))
223
223
224 def notify2(self, name, old, new):
224 def notify2(self, name, old, new):
225 self._notify2.append((name, old, new))
225 self._notify2.append((name, old, new))
226
226
227 def test_notify_all(self):
227 def test_notify_all(self):
228
228
229 class A(HasTraits):
229 class A(HasTraits):
230 a = Int
230 a = Int
231 b = Float
231 b = Float
232
232
233 a = A()
233 a = A()
234 a.on_trait_change(self.notify1)
234 a.on_trait_change(self.notify1)
235 a.a = 0
235 a.a = 0
236 self.assertEquals(len(self._notify1),0)
236 self.assertEquals(len(self._notify1),0)
237 a.b = 0.0
237 a.b = 0.0
238 self.assertEquals(len(self._notify1),0)
238 self.assertEquals(len(self._notify1),0)
239 a.a = 10
239 a.a = 10
240 self.assert_(('a',0,10) in self._notify1)
240 self.assert_(('a',0,10) in self._notify1)
241 a.b = 10.0
241 a.b = 10.0
242 self.assert_(('b',0.0,10.0) in self._notify1)
242 self.assert_(('b',0.0,10.0) in self._notify1)
243 self.assertRaises(TraitError,setattr,a,'a','bad string')
243 self.assertRaises(TraitError,setattr,a,'a','bad string')
244 self.assertRaises(TraitError,setattr,a,'b','bad string')
244 self.assertRaises(TraitError,setattr,a,'b','bad string')
245 self._notify1 = []
245 self._notify1 = []
246 a.on_trait_change(self.notify1,remove=True)
246 a.on_trait_change(self.notify1,remove=True)
247 a.a = 20
247 a.a = 20
248 a.b = 20.0
248 a.b = 20.0
249 self.assertEquals(len(self._notify1),0)
249 self.assertEquals(len(self._notify1),0)
250
250
251 def test_notify_one(self):
251 def test_notify_one(self):
252
252
253 class A(HasTraits):
253 class A(HasTraits):
254 a = Int
254 a = Int
255 b = Float
255 b = Float
256
256
257 a = A()
257 a = A()
258 a.on_trait_change(self.notify1, 'a')
258 a.on_trait_change(self.notify1, 'a')
259 a.a = 0
259 a.a = 0
260 self.assertEquals(len(self._notify1),0)
260 self.assertEquals(len(self._notify1),0)
261 a.a = 10
261 a.a = 10
262 self.assert_(('a',0,10) in self._notify1)
262 self.assert_(('a',0,10) in self._notify1)
263 self.assertRaises(TraitError,setattr,a,'a','bad string')
263 self.assertRaises(TraitError,setattr,a,'a','bad string')
264
264
265 def test_subclass(self):
265 def test_subclass(self):
266
266
267 class A(HasTraits):
267 class A(HasTraits):
268 a = Int
268 a = Int
269
269
270 class B(A):
270 class B(A):
271 b = Float
271 b = Float
272
272
273 b = B()
273 b = B()
274 self.assertEquals(b.a,0)
274 self.assertEquals(b.a,0)
275 self.assertEquals(b.b,0.0)
275 self.assertEquals(b.b,0.0)
276 b.a = 100
276 b.a = 100
277 b.b = 100.0
277 b.b = 100.0
278 self.assertEquals(b.a,100)
278 self.assertEquals(b.a,100)
279 self.assertEquals(b.b,100.0)
279 self.assertEquals(b.b,100.0)
280
280
281 def test_notify_subclass(self):
281 def test_notify_subclass(self):
282
282
283 class A(HasTraits):
283 class A(HasTraits):
284 a = Int
284 a = Int
285
285
286 class B(A):
286 class B(A):
287 b = Float
287 b = Float
288
288
289 b = B()
289 b = B()
290 b.on_trait_change(self.notify1, 'a')
290 b.on_trait_change(self.notify1, 'a')
291 b.on_trait_change(self.notify2, 'b')
291 b.on_trait_change(self.notify2, 'b')
292 b.a = 0
292 b.a = 0
293 b.b = 0.0
293 b.b = 0.0
294 self.assertEquals(len(self._notify1),0)
294 self.assertEquals(len(self._notify1),0)
295 self.assertEquals(len(self._notify2),0)
295 self.assertEquals(len(self._notify2),0)
296 b.a = 10
296 b.a = 10
297 b.b = 10.0
297 b.b = 10.0
298 self.assert_(('a',0,10) in self._notify1)
298 self.assert_(('a',0,10) in self._notify1)
299 self.assert_(('b',0.0,10.0) in self._notify2)
299 self.assert_(('b',0.0,10.0) in self._notify2)
300
300
301 def test_static_notify(self):
301 def test_static_notify(self):
302
302
303 class A(HasTraits):
303 class A(HasTraits):
304 a = Int
304 a = Int
305 _notify1 = []
305 _notify1 = []
306 def _a_changed(self, name, old, new):
306 def _a_changed(self, name, old, new):
307 self._notify1.append((name, old, new))
307 self._notify1.append((name, old, new))
308
308
309 a = A()
309 a = A()
310 a.a = 0
310 a.a = 0
311 # This is broken!!!
311 # This is broken!!!
312 self.assertEquals(len(a._notify1),0)
312 self.assertEquals(len(a._notify1),0)
313 a.a = 10
313 a.a = 10
314 self.assert_(('a',0,10) in a._notify1)
314 self.assert_(('a',0,10) in a._notify1)
315
315
316 class B(A):
316 class B(A):
317 b = Float
317 b = Float
318 _notify2 = []
318 _notify2 = []
319 def _b_changed(self, name, old, new):
319 def _b_changed(self, name, old, new):
320 self._notify2.append((name, old, new))
320 self._notify2.append((name, old, new))
321
321
322 b = B()
322 b = B()
323 b.a = 10
323 b.a = 10
324 b.b = 10.0
324 b.b = 10.0
325 self.assert_(('a',0,10) in b._notify1)
325 self.assert_(('a',0,10) in b._notify1)
326 self.assert_(('b',0.0,10.0) in b._notify2)
326 self.assert_(('b',0.0,10.0) in b._notify2)
327
327
328 def test_notify_args(self):
328 def test_notify_args(self):
329
329
330 def callback0():
330 def callback0():
331 self.cb = ()
331 self.cb = ()
332 def callback1(name):
332 def callback1(name):
333 self.cb = (name,)
333 self.cb = (name,)
334 def callback2(name, new):
334 def callback2(name, new):
335 self.cb = (name, new)
335 self.cb = (name, new)
336 def callback3(name, old, new):
336 def callback3(name, old, new):
337 self.cb = (name, old, new)
337 self.cb = (name, old, new)
338
338
339 class A(HasTraits):
339 class A(HasTraits):
340 a = Int
340 a = Int
341
341
342 a = A()
342 a = A()
343 a.on_trait_change(callback0, 'a')
343 a.on_trait_change(callback0, 'a')
344 a.a = 10
344 a.a = 10
345 self.assertEquals(self.cb,())
345 self.assertEquals(self.cb,())
346 a.on_trait_change(callback0, 'a', remove=True)
346 a.on_trait_change(callback0, 'a', remove=True)
347
347
348 a.on_trait_change(callback1, 'a')
348 a.on_trait_change(callback1, 'a')
349 a.a = 100
349 a.a = 100
350 self.assertEquals(self.cb,('a',))
350 self.assertEquals(self.cb,('a',))
351 a.on_trait_change(callback1, 'a', remove=True)
351 a.on_trait_change(callback1, 'a', remove=True)
352
352
353 a.on_trait_change(callback2, 'a')
353 a.on_trait_change(callback2, 'a')
354 a.a = 1000
354 a.a = 1000
355 self.assertEquals(self.cb,('a',1000))
355 self.assertEquals(self.cb,('a',1000))
356 a.on_trait_change(callback2, 'a', remove=True)
356 a.on_trait_change(callback2, 'a', remove=True)
357
357
358 a.on_trait_change(callback3, 'a')
358 a.on_trait_change(callback3, 'a')
359 a.a = 10000
359 a.a = 10000
360 self.assertEquals(self.cb,('a',1000,10000))
360 self.assertEquals(self.cb,('a',1000,10000))
361 a.on_trait_change(callback3, 'a', remove=True)
361 a.on_trait_change(callback3, 'a', remove=True)
362
362
363 self.assertEquals(len(a._trait_notifiers['a']),0)
363 self.assertEquals(len(a._trait_notifiers['a']),0)
364
364
365
365
366 class TestHasTraits(TestCase):
366 class TestHasTraits(TestCase):
367
367
368 def test_trait_names(self):
368 def test_trait_names(self):
369 class A(HasTraits):
369 class A(HasTraits):
370 i = Int
370 i = Int
371 f = Float
371 f = Float
372 a = A()
372 a = A()
373 self.assertEquals(a.trait_names(),['i','f'])
373 self.assertEquals(sorted(a.trait_names()),['f','i'])
374 self.assertEquals(A.class_trait_names(),['i','f'])
374 self.assertEquals(sorted(A.class_trait_names()),['f','i'])
375
375
376 def test_trait_metadata(self):
376 def test_trait_metadata(self):
377 class A(HasTraits):
377 class A(HasTraits):
378 i = Int(config_key='MY_VALUE')
378 i = Int(config_key='MY_VALUE')
379 a = A()
379 a = A()
380 self.assertEquals(a.trait_metadata('i','config_key'), 'MY_VALUE')
380 self.assertEquals(a.trait_metadata('i','config_key'), 'MY_VALUE')
381
381
382 def test_traits(self):
382 def test_traits(self):
383 class A(HasTraits):
383 class A(HasTraits):
384 i = Int
384 i = Int
385 f = Float
385 f = Float
386 a = A()
386 a = A()
387 self.assertEquals(a.traits(), dict(i=A.i, f=A.f))
387 self.assertEquals(a.traits(), dict(i=A.i, f=A.f))
388 self.assertEquals(A.class_traits(), dict(i=A.i, f=A.f))
388 self.assertEquals(A.class_traits(), dict(i=A.i, f=A.f))
389
389
390 def test_traits_metadata(self):
390 def test_traits_metadata(self):
391 class A(HasTraits):
391 class A(HasTraits):
392 i = Int(config_key='VALUE1', other_thing='VALUE2')
392 i = Int(config_key='VALUE1', other_thing='VALUE2')
393 f = Float(config_key='VALUE3', other_thing='VALUE2')
393 f = Float(config_key='VALUE3', other_thing='VALUE2')
394 j = Int(0)
394 j = Int(0)
395 a = A()
395 a = A()
396 self.assertEquals(a.traits(), dict(i=A.i, f=A.f, j=A.j))
396 self.assertEquals(a.traits(), dict(i=A.i, f=A.f, j=A.j))
397 traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
397 traits = a.traits(config_key='VALUE1', other_thing='VALUE2')
398 self.assertEquals(traits, dict(i=A.i))
398 self.assertEquals(traits, dict(i=A.i))
399
399
400 # This passes, but it shouldn't because I am replicating a bug in
400 # This passes, but it shouldn't because I am replicating a bug in
401 # traits.
401 # traits.
402 traits = a.traits(config_key=lambda v: True)
402 traits = a.traits(config_key=lambda v: True)
403 self.assertEquals(traits, dict(i=A.i, f=A.f, j=A.j))
403 self.assertEquals(traits, dict(i=A.i, f=A.f, j=A.j))
404
404
405 def test_init(self):
405 def test_init(self):
406 class A(HasTraits):
406 class A(HasTraits):
407 i = Int()
407 i = Int()
408 x = Float()
408 x = Float()
409 a = A(i=1, x=10.0)
409 a = A(i=1, x=10.0)
410 self.assertEquals(a.i, 1)
410 self.assertEquals(a.i, 1)
411 self.assertEquals(a.x, 10.0)
411 self.assertEquals(a.x, 10.0)
412
412
413 #-----------------------------------------------------------------------------
413 #-----------------------------------------------------------------------------
414 # Tests for specific trait types
414 # Tests for specific trait types
415 #-----------------------------------------------------------------------------
415 #-----------------------------------------------------------------------------
416
416
417
417
418 class TestType(TestCase):
418 class TestType(TestCase):
419
419
420 def test_default(self):
420 def test_default(self):
421
421
422 class B(object): pass
422 class B(object): pass
423 class A(HasTraits):
423 class A(HasTraits):
424 klass = Type
424 klass = Type
425
425
426 a = A()
426 a = A()
427 self.assertEquals(a.klass, None)
427 self.assertEquals(a.klass, None)
428
428
429 a.klass = B
429 a.klass = B
430 self.assertEquals(a.klass, B)
430 self.assertEquals(a.klass, B)
431 self.assertRaises(TraitError, setattr, a, 'klass', 10)
431 self.assertRaises(TraitError, setattr, a, 'klass', 10)
432
432
433 def test_value(self):
433 def test_value(self):
434
434
435 class B(object): pass
435 class B(object): pass
436 class C(object): pass
436 class C(object): pass
437 class A(HasTraits):
437 class A(HasTraits):
438 klass = Type(B)
438 klass = Type(B)
439
439
440 a = A()
440 a = A()
441 self.assertEquals(a.klass, B)
441 self.assertEquals(a.klass, B)
442 self.assertRaises(TraitError, setattr, a, 'klass', C)
442 self.assertRaises(TraitError, setattr, a, 'klass', C)
443 self.assertRaises(TraitError, setattr, a, 'klass', object)
443 self.assertRaises(TraitError, setattr, a, 'klass', object)
444 a.klass = B
444 a.klass = B
445
445
446 def test_allow_none(self):
446 def test_allow_none(self):
447
447
448 class B(object): pass
448 class B(object): pass
449 class C(B): pass
449 class C(B): pass
450 class A(HasTraits):
450 class A(HasTraits):
451 klass = Type(B, allow_none=False)
451 klass = Type(B, allow_none=False)
452
452
453 a = A()
453 a = A()
454 self.assertEquals(a.klass, B)
454 self.assertEquals(a.klass, B)
455 self.assertRaises(TraitError, setattr, a, 'klass', None)
455 self.assertRaises(TraitError, setattr, a, 'klass', None)
456 a.klass = C
456 a.klass = C
457 self.assertEquals(a.klass, C)
457 self.assertEquals(a.klass, C)
458
458
459 def test_validate_klass(self):
459 def test_validate_klass(self):
460
460
461 class A(HasTraits):
461 class A(HasTraits):
462 klass = Type('no strings allowed')
462 klass = Type('no strings allowed')
463
463
464 self.assertRaises(ImportError, A)
464 self.assertRaises(ImportError, A)
465
465
466 class A(HasTraits):
466 class A(HasTraits):
467 klass = Type('rub.adub.Duck')
467 klass = Type('rub.adub.Duck')
468
468
469 self.assertRaises(ImportError, A)
469 self.assertRaises(ImportError, A)
470
470
471 def test_validate_default(self):
471 def test_validate_default(self):
472
472
473 class B(object): pass
473 class B(object): pass
474 class A(HasTraits):
474 class A(HasTraits):
475 klass = Type('bad default', B)
475 klass = Type('bad default', B)
476
476
477 self.assertRaises(ImportError, A)
477 self.assertRaises(ImportError, A)
478
478
479 class C(HasTraits):
479 class C(HasTraits):
480 klass = Type(None, B, allow_none=False)
480 klass = Type(None, B, allow_none=False)
481
481
482 self.assertRaises(TraitError, C)
482 self.assertRaises(TraitError, C)
483
483
484 def test_str_klass(self):
484 def test_str_klass(self):
485
485
486 class A(HasTraits):
486 class A(HasTraits):
487 klass = Type('IPython.utils.ipstruct.Struct')
487 klass = Type('IPython.utils.ipstruct.Struct')
488
488
489 from IPython.utils.ipstruct import Struct
489 from IPython.utils.ipstruct import Struct
490 a = A()
490 a = A()
491 a.klass = Struct
491 a.klass = Struct
492 self.assertEquals(a.klass, Struct)
492 self.assertEquals(a.klass, Struct)
493
493
494 self.assertRaises(TraitError, setattr, a, 'klass', 10)
494 self.assertRaises(TraitError, setattr, a, 'klass', 10)
495
495
496 class TestInstance(TestCase):
496 class TestInstance(TestCase):
497
497
498 def test_basic(self):
498 def test_basic(self):
499 class Foo(object): pass
499 class Foo(object): pass
500 class Bar(Foo): pass
500 class Bar(Foo): pass
501 class Bah(object): pass
501 class Bah(object): pass
502
502
503 class A(HasTraits):
503 class A(HasTraits):
504 inst = Instance(Foo)
504 inst = Instance(Foo)
505
505
506 a = A()
506 a = A()
507 self.assert_(a.inst is None)
507 self.assert_(a.inst is None)
508 a.inst = Foo()
508 a.inst = Foo()
509 self.assert_(isinstance(a.inst, Foo))
509 self.assert_(isinstance(a.inst, Foo))
510 a.inst = Bar()
510 a.inst = Bar()
511 self.assert_(isinstance(a.inst, Foo))
511 self.assert_(isinstance(a.inst, Foo))
512 self.assertRaises(TraitError, setattr, a, 'inst', Foo)
512 self.assertRaises(TraitError, setattr, a, 'inst', Foo)
513 self.assertRaises(TraitError, setattr, a, 'inst', Bar)
513 self.assertRaises(TraitError, setattr, a, 'inst', Bar)
514 self.assertRaises(TraitError, setattr, a, 'inst', Bah())
514 self.assertRaises(TraitError, setattr, a, 'inst', Bah())
515
515
516 def test_unique_default_value(self):
516 def test_unique_default_value(self):
517 class Foo(object): pass
517 class Foo(object): pass
518 class A(HasTraits):
518 class A(HasTraits):
519 inst = Instance(Foo,(),{})
519 inst = Instance(Foo,(),{})
520
520
521 a = A()
521 a = A()
522 b = A()
522 b = A()
523 self.assert_(a.inst is not b.inst)
523 self.assert_(a.inst is not b.inst)
524
524
525 def test_args_kw(self):
525 def test_args_kw(self):
526 class Foo(object):
526 class Foo(object):
527 def __init__(self, c): self.c = c
527 def __init__(self, c): self.c = c
528 class Bar(object): pass
528 class Bar(object): pass
529 class Bah(object):
529 class Bah(object):
530 def __init__(self, c, d):
530 def __init__(self, c, d):
531 self.c = c; self.d = d
531 self.c = c; self.d = d
532
532
533 class A(HasTraits):
533 class A(HasTraits):
534 inst = Instance(Foo, (10,))
534 inst = Instance(Foo, (10,))
535 a = A()
535 a = A()
536 self.assertEquals(a.inst.c, 10)
536 self.assertEquals(a.inst.c, 10)
537
537
538 class B(HasTraits):
538 class B(HasTraits):
539 inst = Instance(Bah, args=(10,), kw=dict(d=20))
539 inst = Instance(Bah, args=(10,), kw=dict(d=20))
540 b = B()
540 b = B()
541 self.assertEquals(b.inst.c, 10)
541 self.assertEquals(b.inst.c, 10)
542 self.assertEquals(b.inst.d, 20)
542 self.assertEquals(b.inst.d, 20)
543
543
544 class C(HasTraits):
544 class C(HasTraits):
545 inst = Instance(Foo)
545 inst = Instance(Foo)
546 c = C()
546 c = C()
547 self.assert_(c.inst is None)
547 self.assert_(c.inst is None)
548
548
549 def test_bad_default(self):
549 def test_bad_default(self):
550 class Foo(object): pass
550 class Foo(object): pass
551
551
552 class A(HasTraits):
552 class A(HasTraits):
553 inst = Instance(Foo, allow_none=False)
553 inst = Instance(Foo, allow_none=False)
554
554
555 self.assertRaises(TraitError, A)
555 self.assertRaises(TraitError, A)
556
556
557 def test_instance(self):
557 def test_instance(self):
558 class Foo(object): pass
558 class Foo(object): pass
559
559
560 def inner():
560 def inner():
561 class A(HasTraits):
561 class A(HasTraits):
562 inst = Instance(Foo())
562 inst = Instance(Foo())
563
563
564 self.assertRaises(TraitError, inner)
564 self.assertRaises(TraitError, inner)
565
565
566
566
567 class TestThis(TestCase):
567 class TestThis(TestCase):
568
568
569 def test_this_class(self):
569 def test_this_class(self):
570 class Foo(HasTraits):
570 class Foo(HasTraits):
571 this = This
571 this = This
572
572
573 f = Foo()
573 f = Foo()
574 self.assertEquals(f.this, None)
574 self.assertEquals(f.this, None)
575 g = Foo()
575 g = Foo()
576 f.this = g
576 f.this = g
577 self.assertEquals(f.this, g)
577 self.assertEquals(f.this, g)
578 self.assertRaises(TraitError, setattr, f, 'this', 10)
578 self.assertRaises(TraitError, setattr, f, 'this', 10)
579
579
580 def test_this_inst(self):
580 def test_this_inst(self):
581 class Foo(HasTraits):
581 class Foo(HasTraits):
582 this = This()
582 this = This()
583
583
584 f = Foo()
584 f = Foo()
585 f.this = Foo()
585 f.this = Foo()
586 self.assert_(isinstance(f.this, Foo))
586 self.assert_(isinstance(f.this, Foo))
587
587
588 def test_subclass(self):
588 def test_subclass(self):
589 class Foo(HasTraits):
589 class Foo(HasTraits):
590 t = This()
590 t = This()
591 class Bar(Foo):
591 class Bar(Foo):
592 pass
592 pass
593 f = Foo()
593 f = Foo()
594 b = Bar()
594 b = Bar()
595 f.t = b
595 f.t = b
596 b.t = f
596 b.t = f
597 self.assertEquals(f.t, b)
597 self.assertEquals(f.t, b)
598 self.assertEquals(b.t, f)
598 self.assertEquals(b.t, f)
599
599
600 def test_subclass_override(self):
600 def test_subclass_override(self):
601 class Foo(HasTraits):
601 class Foo(HasTraits):
602 t = This()
602 t = This()
603 class Bar(Foo):
603 class Bar(Foo):
604 t = This()
604 t = This()
605 f = Foo()
605 f = Foo()
606 b = Bar()
606 b = Bar()
607 f.t = b
607 f.t = b
608 self.assertEquals(f.t, b)
608 self.assertEquals(f.t, b)
609 self.assertRaises(TraitError, setattr, b, 't', f)
609 self.assertRaises(TraitError, setattr, b, 't', f)
610
610
611 class TraitTestBase(TestCase):
611 class TraitTestBase(TestCase):
612 """A best testing class for basic trait types."""
612 """A best testing class for basic trait types."""
613
613
614 def assign(self, value):
614 def assign(self, value):
615 self.obj.value = value
615 self.obj.value = value
616
616
617 def coerce(self, value):
617 def coerce(self, value):
618 return value
618 return value
619
619
620 def test_good_values(self):
620 def test_good_values(self):
621 if hasattr(self, '_good_values'):
621 if hasattr(self, '_good_values'):
622 for value in self._good_values:
622 for value in self._good_values:
623 self.assign(value)
623 self.assign(value)
624 self.assertEquals(self.obj.value, self.coerce(value))
624 self.assertEquals(self.obj.value, self.coerce(value))
625
625
626 def test_bad_values(self):
626 def test_bad_values(self):
627 if hasattr(self, '_bad_values'):
627 if hasattr(self, '_bad_values'):
628 for value in self._bad_values:
628 for value in self._bad_values:
629 try:
629 try:
630 self.assertRaises(TraitError, self.assign, value)
630 self.assertRaises(TraitError, self.assign, value)
631 except AssertionError:
631 except AssertionError:
632 assert False, value
632 assert False, value
633
633
634 def test_default_value(self):
634 def test_default_value(self):
635 if hasattr(self, '_default_value'):
635 if hasattr(self, '_default_value'):
636 self.assertEquals(self._default_value, self.obj.value)
636 self.assertEquals(self._default_value, self.obj.value)
637
637
638 def tearDown(self):
638 def tearDown(self):
639 # restore default value after tests, if set
639 # restore default value after tests, if set
640 if hasattr(self, '_default_value'):
640 if hasattr(self, '_default_value'):
641 self.obj.value = self._default_value
641 self.obj.value = self._default_value
642
642
643
643
644 class AnyTrait(HasTraits):
644 class AnyTrait(HasTraits):
645
645
646 value = Any
646 value = Any
647
647
648 class AnyTraitTest(TraitTestBase):
648 class AnyTraitTest(TraitTestBase):
649
649
650 obj = AnyTrait()
650 obj = AnyTrait()
651
651
652 _default_value = None
652 _default_value = None
653 _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10},(10,), None, 1j]
653 _good_values = [10.0, 'ten', u'ten', [10], {'ten': 10},(10,), None, 1j]
654 _bad_values = []
654 _bad_values = []
655
655
656
656
657 class IntTrait(HasTraits):
657 class IntTrait(HasTraits):
658
658
659 value = Int(99)
659 value = Int(99)
660
660
661 class TestInt(TraitTestBase):
661 class TestInt(TraitTestBase):
662
662
663 obj = IntTrait()
663 obj = IntTrait()
664 _default_value = 99
664 _default_value = 99
665 _good_values = [10, -10]
665 _good_values = [10, -10]
666 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, 1j,
666 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None, 1j,
667 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L',
667 10.1, -10.1, '10L', '-10L', '10.1', '-10.1', u'10L',
668 u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10']
668 u'-10L', u'10.1', u'-10.1', '10', '-10', u'10', u'-10']
669 if not py3compat.PY3:
669 if not py3compat.PY3:
670 _bad_values.extend([10L, -10L, 10*sys.maxint, -10*sys.maxint])
670 _bad_values.extend([10L, -10L, 10*sys.maxint, -10*sys.maxint])
671
671
672
672
673 class LongTrait(HasTraits):
673 class LongTrait(HasTraits):
674
674
675 value = Long(99L)
675 value = Long(99L)
676
676
677 class TestLong(TraitTestBase):
677 class TestLong(TraitTestBase):
678
678
679 obj = LongTrait()
679 obj = LongTrait()
680
680
681 _default_value = 99L
681 _default_value = 99L
682 _good_values = [10, -10, 10L, -10L]
682 _good_values = [10, -10, 10L, -10L]
683 _bad_values = ['ten', u'ten', [10], [10l], {'ten': 10},(10,),(10L,),
683 _bad_values = ['ten', u'ten', [10], [10l], {'ten': 10},(10,),(10L,),
684 None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
684 None, 1j, 10.1, -10.1, '10', '-10', '10L', '-10L', '10.1',
685 '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1',
685 '-10.1', u'10', u'-10', u'10L', u'-10L', u'10.1',
686 u'-10.1']
686 u'-10.1']
687 if not py3compat.PY3:
687 if not py3compat.PY3:
688 # maxint undefined on py3, because int == long
688 # maxint undefined on py3, because int == long
689 _good_values.extend([10*sys.maxint, -10*sys.maxint])
689 _good_values.extend([10*sys.maxint, -10*sys.maxint])
690
690
691 @skipif(py3compat.PY3, "not relevant on py3")
691 @skipif(py3compat.PY3, "not relevant on py3")
692 def test_cast_small(self):
692 def test_cast_small(self):
693 """Long casts ints to long"""
693 """Long casts ints to long"""
694 self.obj.value = 10
694 self.obj.value = 10
695 self.assertEquals(type(self.obj.value), long)
695 self.assertEquals(type(self.obj.value), long)
696
696
697
697
698 class IntegerTrait(HasTraits):
698 class IntegerTrait(HasTraits):
699 value = Integer(1)
699 value = Integer(1)
700
700
701 class TestInteger(TestLong):
701 class TestInteger(TestLong):
702 obj = IntegerTrait()
702 obj = IntegerTrait()
703 _default_value = 1
703 _default_value = 1
704
704
705 def coerce(self, n):
705 def coerce(self, n):
706 return int(n)
706 return int(n)
707
707
708 @skipif(py3compat.PY3, "not relevant on py3")
708 @skipif(py3compat.PY3, "not relevant on py3")
709 def test_cast_small(self):
709 def test_cast_small(self):
710 """Integer casts small longs to int"""
710 """Integer casts small longs to int"""
711 if py3compat.PY3:
711 if py3compat.PY3:
712 raise SkipTest("not relevant on py3")
712 raise SkipTest("not relevant on py3")
713
713
714 self.obj.value = 100L
714 self.obj.value = 100L
715 self.assertEquals(type(self.obj.value), int)
715 self.assertEquals(type(self.obj.value), int)
716
716
717
717
718 class FloatTrait(HasTraits):
718 class FloatTrait(HasTraits):
719
719
720 value = Float(99.0)
720 value = Float(99.0)
721
721
722 class TestFloat(TraitTestBase):
722 class TestFloat(TraitTestBase):
723
723
724 obj = FloatTrait()
724 obj = FloatTrait()
725
725
726 _default_value = 99.0
726 _default_value = 99.0
727 _good_values = [10, -10, 10.1, -10.1]
727 _good_values = [10, -10, 10.1, -10.1]
728 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None,
728 _bad_values = ['ten', u'ten', [10], {'ten': 10},(10,), None,
729 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10',
729 1j, '10', '-10', '10L', '-10L', '10.1', '-10.1', u'10',
730 u'-10', u'10L', u'-10L', u'10.1', u'-10.1']
730 u'-10', u'10L', u'-10L', u'10.1', u'-10.1']
731 if not py3compat.PY3:
731 if not py3compat.PY3:
732 _bad_values.extend([10L, -10L])
732 _bad_values.extend([10L, -10L])
733
733
734
734
735 class ComplexTrait(HasTraits):
735 class ComplexTrait(HasTraits):
736
736
737 value = Complex(99.0-99.0j)
737 value = Complex(99.0-99.0j)
738
738
739 class TestComplex(TraitTestBase):
739 class TestComplex(TraitTestBase):
740
740
741 obj = ComplexTrait()
741 obj = ComplexTrait()
742
742
743 _default_value = 99.0-99.0j
743 _default_value = 99.0-99.0j
744 _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j,
744 _good_values = [10, -10, 10.1, -10.1, 10j, 10+10j, 10-10j,
745 10.1j, 10.1+10.1j, 10.1-10.1j]
745 10.1j, 10.1+10.1j, 10.1-10.1j]
746 _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None]
746 _bad_values = [u'10L', u'-10L', 'ten', [10], {'ten': 10},(10,), None]
747 if not py3compat.PY3:
747 if not py3compat.PY3:
748 _bad_values.extend([10L, -10L])
748 _bad_values.extend([10L, -10L])
749
749
750
750
751 class BytesTrait(HasTraits):
751 class BytesTrait(HasTraits):
752
752
753 value = Bytes(b'string')
753 value = Bytes(b'string')
754
754
755 class TestBytes(TraitTestBase):
755 class TestBytes(TraitTestBase):
756
756
757 obj = BytesTrait()
757 obj = BytesTrait()
758
758
759 _default_value = b'string'
759 _default_value = b'string'
760 _good_values = [b'10', b'-10', b'10L',
760 _good_values = [b'10', b'-10', b'10L',
761 b'-10L', b'10.1', b'-10.1', b'string']
761 b'-10L', b'10.1', b'-10.1', b'string']
762 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j, [10],
762 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j, [10],
763 ['ten'],{'ten': 10},(10,), None, u'string']
763 ['ten'],{'ten': 10},(10,), None, u'string']
764
764
765
765
766 class UnicodeTrait(HasTraits):
766 class UnicodeTrait(HasTraits):
767
767
768 value = Unicode(u'unicode')
768 value = Unicode(u'unicode')
769
769
770 class TestUnicode(TraitTestBase):
770 class TestUnicode(TraitTestBase):
771
771
772 obj = UnicodeTrait()
772 obj = UnicodeTrait()
773
773
774 _default_value = u'unicode'
774 _default_value = u'unicode'
775 _good_values = ['10', '-10', '10L', '-10L', '10.1',
775 _good_values = ['10', '-10', '10L', '-10L', '10.1',
776 '-10.1', '', u'', 'string', u'string', u"€"]
776 '-10.1', '', u'', 'string', u'string', u"€"]
777 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j,
777 _bad_values = [10, -10, 10L, -10L, 10.1, -10.1, 1j,
778 [10], ['ten'], [u'ten'], {'ten': 10},(10,), None]
778 [10], ['ten'], [u'ten'], {'ten': 10},(10,), None]
779
779
780
780
781 class ObjectNameTrait(HasTraits):
781 class ObjectNameTrait(HasTraits):
782 value = ObjectName("abc")
782 value = ObjectName("abc")
783
783
784 class TestObjectName(TraitTestBase):
784 class TestObjectName(TraitTestBase):
785 obj = ObjectNameTrait()
785 obj = ObjectNameTrait()
786
786
787 _default_value = "abc"
787 _default_value = "abc"
788 _good_values = ["a", "gh", "g9", "g_", "_G", u"a345_"]
788 _good_values = ["a", "gh", "g9", "g_", "_G", u"a345_"]
789 _bad_values = [1, "", u"€", "9g", "!", "#abc", "aj@", "a.b", "a()", "a[0]",
789 _bad_values = [1, "", u"€", "9g", "!", "#abc", "aj@", "a.b", "a()", "a[0]",
790 object(), object]
790 object(), object]
791 if sys.version_info[0] < 3:
791 if sys.version_info[0] < 3:
792 _bad_values.append(u"ΓΎ")
792 _bad_values.append(u"ΓΎ")
793 else:
793 else:
794 _good_values.append(u"ΓΎ") # ΓΎ=1 is valid in Python 3 (PEP 3131).
794 _good_values.append(u"ΓΎ") # ΓΎ=1 is valid in Python 3 (PEP 3131).
795
795
796
796
797 class DottedObjectNameTrait(HasTraits):
797 class DottedObjectNameTrait(HasTraits):
798 value = DottedObjectName("a.b")
798 value = DottedObjectName("a.b")
799
799
800 class TestDottedObjectName(TraitTestBase):
800 class TestDottedObjectName(TraitTestBase):
801 obj = DottedObjectNameTrait()
801 obj = DottedObjectNameTrait()
802
802
803 _default_value = "a.b"
803 _default_value = "a.b"
804 _good_values = ["A", "y.t", "y765.__repr__", "os.path.join", u"os.path.join"]
804 _good_values = ["A", "y.t", "y765.__repr__", "os.path.join", u"os.path.join"]
805 _bad_values = [1, u"abc.€", "_.@", ".", ".abc", "abc.", ".abc."]
805 _bad_values = [1, u"abc.€", "_.@", ".", ".abc", "abc.", ".abc."]
806 if sys.version_info[0] < 3:
806 if sys.version_info[0] < 3:
807 _bad_values.append(u"t.ΓΎ")
807 _bad_values.append(u"t.ΓΎ")
808 else:
808 else:
809 _good_values.append(u"t.ΓΎ")
809 _good_values.append(u"t.ΓΎ")
810
810
811
811
812 class TCPAddressTrait(HasTraits):
812 class TCPAddressTrait(HasTraits):
813
813
814 value = TCPAddress()
814 value = TCPAddress()
815
815
816 class TestTCPAddress(TraitTestBase):
816 class TestTCPAddress(TraitTestBase):
817
817
818 obj = TCPAddressTrait()
818 obj = TCPAddressTrait()
819
819
820 _default_value = ('127.0.0.1',0)
820 _default_value = ('127.0.0.1',0)
821 _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)]
821 _good_values = [('localhost',0),('192.168.0.1',1000),('www.google.com',80)]
822 _bad_values = [(0,0),('localhost',10.0),('localhost',-1)]
822 _bad_values = [(0,0),('localhost',10.0),('localhost',-1)]
823
823
824 class ListTrait(HasTraits):
824 class ListTrait(HasTraits):
825
825
826 value = List(Int)
826 value = List(Int)
827
827
828 class TestList(TraitTestBase):
828 class TestList(TraitTestBase):
829
829
830 obj = ListTrait()
830 obj = ListTrait()
831
831
832 _default_value = []
832 _default_value = []
833 _good_values = [[], [1], range(10)]
833 _good_values = [[], [1], range(10)]
834 _bad_values = [10, [1,'a'], 'a', (1,2)]
834 _bad_values = [10, [1,'a'], 'a', (1,2)]
835
835
836 class LenListTrait(HasTraits):
836 class LenListTrait(HasTraits):
837
837
838 value = List(Int, [0], minlen=1, maxlen=2)
838 value = List(Int, [0], minlen=1, maxlen=2)
839
839
840 class TestLenList(TraitTestBase):
840 class TestLenList(TraitTestBase):
841
841
842 obj = LenListTrait()
842 obj = LenListTrait()
843
843
844 _default_value = [0]
844 _default_value = [0]
845 _good_values = [[1], range(2)]
845 _good_values = [[1], range(2)]
846 _bad_values = [10, [1,'a'], 'a', (1,2), [], range(3)]
846 _bad_values = [10, [1,'a'], 'a', (1,2), [], range(3)]
847
847
848 class TupleTrait(HasTraits):
848 class TupleTrait(HasTraits):
849
849
850 value = Tuple(Int)
850 value = Tuple(Int)
851
851
852 class TestTupleTrait(TraitTestBase):
852 class TestTupleTrait(TraitTestBase):
853
853
854 obj = TupleTrait()
854 obj = TupleTrait()
855
855
856 _default_value = None
856 _default_value = None
857 _good_values = [(1,), None,(0,)]
857 _good_values = [(1,), None,(0,)]
858 _bad_values = [10, (1,2), [1],('a'), ()]
858 _bad_values = [10, (1,2), [1],('a'), ()]
859
859
860 def test_invalid_args(self):
860 def test_invalid_args(self):
861 self.assertRaises(TypeError, Tuple, 5)
861 self.assertRaises(TypeError, Tuple, 5)
862 self.assertRaises(TypeError, Tuple, default_value='hello')
862 self.assertRaises(TypeError, Tuple, default_value='hello')
863 t = Tuple(Int, CBytes, default_value=(1,5))
863 t = Tuple(Int, CBytes, default_value=(1,5))
864
864
865 class LooseTupleTrait(HasTraits):
865 class LooseTupleTrait(HasTraits):
866
866
867 value = Tuple((1,2,3))
867 value = Tuple((1,2,3))
868
868
869 class TestLooseTupleTrait(TraitTestBase):
869 class TestLooseTupleTrait(TraitTestBase):
870
870
871 obj = LooseTupleTrait()
871 obj = LooseTupleTrait()
872
872
873 _default_value = (1,2,3)
873 _default_value = (1,2,3)
874 _good_values = [(1,), None, (0,), tuple(range(5)), tuple('hello'), ('a',5), ()]
874 _good_values = [(1,), None, (0,), tuple(range(5)), tuple('hello'), ('a',5), ()]
875 _bad_values = [10, 'hello', [1], []]
875 _bad_values = [10, 'hello', [1], []]
876
876
877 def test_invalid_args(self):
877 def test_invalid_args(self):
878 self.assertRaises(TypeError, Tuple, 5)
878 self.assertRaises(TypeError, Tuple, 5)
879 self.assertRaises(TypeError, Tuple, default_value='hello')
879 self.assertRaises(TypeError, Tuple, default_value='hello')
880 t = Tuple(Int, CBytes, default_value=(1,5))
880 t = Tuple(Int, CBytes, default_value=(1,5))
881
881
882
882
883 class MultiTupleTrait(HasTraits):
883 class MultiTupleTrait(HasTraits):
884
884
885 value = Tuple(Int, Bytes, default_value=[99,b'bottles'])
885 value = Tuple(Int, Bytes, default_value=[99,b'bottles'])
886
886
887 class TestMultiTuple(TraitTestBase):
887 class TestMultiTuple(TraitTestBase):
888
888
889 obj = MultiTupleTrait()
889 obj = MultiTupleTrait()
890
890
891 _default_value = (99,b'bottles')
891 _default_value = (99,b'bottles')
892 _good_values = [(1,b'a'), (2,b'b')]
892 _good_values = [(1,b'a'), (2,b'b')]
893 _bad_values = ((),10, b'a', (1,b'a',3), (b'a',1), (1, u'a'))
893 _bad_values = ((),10, b'a', (1,b'a',3), (b'a',1), (1, u'a'))
894
894
895 class CRegExpTrait(HasTraits):
895 class CRegExpTrait(HasTraits):
896
896
897 value = CRegExp(r'')
897 value = CRegExp(r'')
898
898
899 class TestCRegExp(TraitTestBase):
899 class TestCRegExp(TraitTestBase):
900
900
901 def coerce(self, value):
901 def coerce(self, value):
902 return re.compile(value)
902 return re.compile(value)
903
903
904 obj = CRegExpTrait()
904 obj = CRegExpTrait()
905
905
906 _default_value = re.compile(r'')
906 _default_value = re.compile(r'')
907 _good_values = [r'\d+', re.compile(r'\d+')]
907 _good_values = [r'\d+', re.compile(r'\d+')]
908 _bad_values = [r'(', None, ()]
908 _bad_values = [r'(', None, ()]
General Comments 0
You need to be logged in to leave comments. Login now