Debian Codegraph @

lib-python/3/test/test_funcattrs.py

raw symbols SCIP
1 import textwrap
2 import types
3 import unittest
4 from test import support
5
6
7 def global_function():
8 def inner_function():
9 class LocalClass:
10 pass
11 global inner_global_function
12 def inner_global_function():
13 def inner_function2():
14 pass
15 return inner_function2
16 return LocalClass
17 return lambda: inner_function
18
19
20 class FuncAttrsTest(unittest.TestCase):
21 def setUp(self):
22 class F:
23 def a(self):
24 pass
25 def b():
26 return 3
27 self.fi = F()
28 self.F = F
29 self.b = b
30
31 def cannot_set_attr(self, obj, name, value, exceptions):
32 try:
33 setattr(obj, name, value)
34 except exceptions:
35 pass
36 else:
37 self.fail("shouldn't be able to set %s to %r" % (name, value))
38 try:
39 delattr(obj, name)
40 except exceptions:
41 pass
42 else:
43 self.fail("shouldn't be able to del %s" % name)
44
45
46 class FunctionPropertiesTest(FuncAttrsTest):
47 # Include the external setUp method that is common to all tests
48 def test_module(self):
49 self.assertEqual(self.b.__module__, __name__)
50
51 def test_dir_includes_correct_attrs(self):
52 self.b.known_attr = 7
53 self.assertIn('known_attr', dir(self.b),
54 "set attributes not in dir listing of method")
55 # Test on underlying function object of method
56 self.F.a.known_attr = 7
57 self.assertIn('known_attr', dir(self.fi.a), "set attribute on function "
58 "implementations, should show up in next dir")
59
60 def test_duplicate_function_equality(self):
61 # Body of `duplicate' is the exact same as self.b
62 def duplicate():
63 'my docstring'
64 return 3
65 self.assertNotEqual(self.b, duplicate)
66
67 def test_copying___code__(self):
68 def test(): pass
69 self.assertEqual(test(), None)
70 test.__code__ = self.b.__code__
71 self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily
72
73 def test___globals__(self):
74 self.assertIs(self.b.__globals__, globals())
75 self.cannot_set_attr(self.b, '__globals__', 2,
76 (AttributeError, TypeError))
77
78 @support.cpython_only
79 def test___builtins__(self):
80 self.assertIs(self.b.__builtins__, __builtins__)
81 self.cannot_set_attr(self.b, '__builtins__', 2,
82 (AttributeError, TypeError))
83
84 # bpo-42990: If globals is specified and has no "__builtins__" key,
85 # a function inherits the current builtins namespace.
86 def func(s): return len(s)
87 ns = {}
88 func2 = type(func)(func.__code__, ns)
89 self.assertIs(func2.__globals__, ns)
90 self.assertIs(func2.__builtins__, __builtins__)
91
92 # Make sure that the function actually works.
93 self.assertEqual(func2("abc"), 3)
94 self.assertEqual(ns, {})
95
96 # Define functions using exec() with different builtins,
97 # and test inheritance when globals has no "__builtins__" key
98 code = textwrap.dedent("""
99 def func3(s): pass
100 func4 = type(func3)(func3.__code__, {})
101 """)
102 safe_builtins = {'None': None}
103 ns = {'type': type, '__builtins__': safe_builtins}
104 exec(code, ns)
105 self.assertIs(ns['func3'].__builtins__, safe_builtins)
106 self.assertIs(ns['func4'].__builtins__, safe_builtins)
107 self.assertIs(ns['func3'].__globals__['__builtins__'], safe_builtins)
108 self.assertNotIn('__builtins__', ns['func4'].__globals__)
109
110 def test___closure__(self):
111 a = 12
112 def f(): print(a)
113 c = f.__closure__
114 self.assertIsInstance(c, tuple)
115 self.assertEqual(len(c), 1)
116 # don't have a type object handy
117 self.assertEqual(c[0].__class__.__name__, "cell")
118 self.cannot_set_attr(f, "__closure__", c, (AttributeError, TypeError))
119
120 def test_cell_new(self):
121 cell_obj = types.CellType(1)
122 self.assertEqual(cell_obj.cell_contents, 1)
123
124 cell_obj = types.CellType()
125 msg = "shouldn't be able to read an empty cell"
126 with self.assertRaises(ValueError, msg=msg):
127 cell_obj.cell_contents
128
129 def test_empty_cell(self):
130 def f(): print(a)
131 try:
132 f.__closure__[0].cell_contents
133 except ValueError:
134 pass
135 else:
136 self.fail("shouldn't be able to read an empty cell")
137 a = 12
138
139 def test_set_cell(self):
140 a = 12
141 def f(): return a
142 c = f.__closure__
143 c[0].cell_contents = 9
144 self.assertEqual(c[0].cell_contents, 9)
145 self.assertEqual(f(), 9)
146 self.assertEqual(a, 9)
147 del c[0].cell_contents
148 try:
149 c[0].cell_contents
150 except ValueError:
151 pass
152 else:
153 self.fail("shouldn't be able to read an empty cell")
154 with self.assertRaises(NameError):
155 f()
156 with self.assertRaises(UnboundLocalError):
157 print(a)
158
159 def test___name__(self):
160 self.assertEqual(self.b.__name__, 'b')
161 self.b.__name__ = 'c'
162 self.assertEqual(self.b.__name__, 'c')
163 self.b.__name__ = 'd'
164 self.assertEqual(self.b.__name__, 'd')
165 # __name__ and __name__ must be a string
166 self.cannot_set_attr(self.b, '__name__', 7, (AttributeError, TypeError))
167 # __name__ must be available when in restricted mode. Exec will raise
168 # AttributeError if __name__ is not available on f.
169 s = """def f(): pass\nf.__name__"""
170 exec(s, {'__builtins__': {}})
171 # Test on methods, too
172 self.assertEqual(self.fi.a.__name__, 'a')
173 self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError)
174
175 def test___qualname__(self):
176 # PEP 3155
177 self.assertEqual(self.b.__qualname__, 'FuncAttrsTest.setUp.<locals>.b')
178 self.assertEqual(FuncAttrsTest.setUp.__qualname__, 'FuncAttrsTest.setUp')
179 self.assertEqual(global_function.__qualname__, 'global_function')
180 self.assertEqual(global_function().__qualname__,
181 'global_function.<locals>.<lambda>')
182 self.assertEqual(global_function()().__qualname__,
183 'global_function.<locals>.inner_function')
184 self.assertEqual(global_function()()().__qualname__,
185 'global_function.<locals>.inner_function.<locals>.LocalClass')
186 self.assertEqual(inner_global_function.__qualname__, 'inner_global_function')
187 self.assertEqual(inner_global_function().__qualname__, 'inner_global_function.<locals>.inner_function2')
188 self.b.__qualname__ = 'c'
189 self.assertEqual(self.b.__qualname__, 'c')
190 self.b.__qualname__ = 'd'
191 self.assertEqual(self.b.__qualname__, 'd')
192 # __qualname__ must be a string
193 self.cannot_set_attr(self.b, '__qualname__', 7,
194 (TypeError, AttributeError))
195
196 def test___code__(self):
197 num_one, num_two = 7, 8
198 def a(): pass
199 def b(): return 12
200 def c(): return num_one
201 def d(): return num_two
202 def e(): return num_one, num_two
203 for func in [a, b, c, d, e]:
204 self.assertEqual(type(func.__code__), types.CodeType)
205 self.assertEqual(c(), 7)
206 self.assertEqual(d(), 8)
207 d.__code__ = c.__code__
208 self.assertEqual(c.__code__, d.__code__)
209 self.assertEqual(c(), 7)
210 # self.assertEqual(d(), 7)
211 try:
212 b.__code__ = c.__code__
213 except ValueError:
214 pass
215 else:
216 self.fail("__code__ with different numbers of free vars should "
217 "not be possible")
218 try:
219 e.__code__ = d.__code__
220 except ValueError:
221 pass
222 else:
223 self.fail("__code__ with different numbers of free vars should "
224 "not be possible")
225
226 def test_blank_func_defaults(self):
227 self.assertEqual(self.b.__defaults__, None)
228 del self.b.__defaults__
229 self.assertEqual(self.b.__defaults__, None)
230
231 def test_func_default_args(self):
232 def first_func(a, b):
233 return a+b
234 def second_func(a=1, b=2):
235 return a+b
236 self.assertEqual(first_func.__defaults__, None)
237 self.assertEqual(second_func.__defaults__, (1, 2))
238 first_func.__defaults__ = (1, 2)
239 self.assertEqual(first_func.__defaults__, (1, 2))
240 self.assertEqual(first_func(), 3)
241 self.assertEqual(first_func(3), 5)
242 self.assertEqual(first_func(3, 5), 8)
243 del second_func.__defaults__
244 self.assertEqual(second_func.__defaults__, None)
245 try:
246 second_func()
247 except TypeError:
248 pass
249 else:
250 self.fail("__defaults__ does not update; deleting it does not "
251 "remove requirement")
252
253
254 class InstancemethodAttrTest(FuncAttrsTest):
255
256 def test___class__(self):
257 self.assertEqual(self.fi.a.__self__.__class__, self.F)
258 self.cannot_set_attr(self.fi.a, "__class__", self.F, (AttributeError, TypeError))
259
260 def test___func__(self):
261 self.assertEqual(self.fi.a.__func__, self.F.a)
262 self.cannot_set_attr(self.fi.a, "__func__", self.F.a, (AttributeError, TypeError))
263
264 def test___self__(self):
265 self.assertEqual(self.fi.a.__self__, self.fi)
266 self.cannot_set_attr(self.fi.a, "__self__", self.fi, (AttributeError, TypeError))
267
268 def test___func___non_method(self):
269 # Behavior should be the same when a method is added via an attr
270 # assignment
271 self.fi.id = types.MethodType(id, self.fi)
272 self.assertEqual(self.fi.id(), id(self.fi))
273 # Test usage
274 try:
275 self.fi.id.unknown_attr
276 except AttributeError:
277 pass
278 else:
279 self.fail("using unknown attributes should raise AttributeError")
280 # Test assignment and deletion
281 self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError)
282
283
284 class ArbitraryFunctionAttrTest(FuncAttrsTest):
285 def test_set_attr(self):
286 self.b.known_attr = 7
287 self.assertEqual(self.b.known_attr, 7)
288 try:
289 self.fi.a.known_attr = 7
290 except AttributeError:
291 pass
292 else:
293 self.fail("setting attributes on methods should raise error")
294
295 def test_delete_unknown_attr(self):
296 try:
297 del self.b.unknown_attr
298 except AttributeError:
299 pass
300 else:
301 self.fail("deleting unknown attribute should raise TypeError")
302
303 def test_unset_attr(self):
304 for func in [self.b, self.fi.a]:
305 try:
306 func.non_existent_attr
307 except AttributeError:
308 pass
309 else:
310 self.fail("using unknown attributes should raise "
311 "AttributeError")
312
313
314 class FunctionDictsTest(FuncAttrsTest):
315 def test_setting_dict_to_invalid(self):
316 self.cannot_set_attr(self.b, '__dict__', None, (AttributeError, TypeError))
317 from collections import UserDict
318 d = UserDict({'known_attr': 7})
319 self.cannot_set_attr(self.fi.a.__func__, '__dict__', d, (AttributeError, TypeError))
320
321 def test_setting_dict_to_valid(self):
322 d = {'known_attr': 7}
323 self.b.__dict__ = d
324 # Test assignment
325 self.assertIs(d, self.b.__dict__)
326 # ... and on all the different ways of referencing the method's func
327 self.F.a.__dict__ = d
328 self.assertIs(d, self.fi.a.__func__.__dict__)
329 self.assertIs(d, self.fi.a.__dict__)
330 # Test value
331 self.assertEqual(self.b.known_attr, 7)
332 self.assertEqual(self.b.__dict__['known_attr'], 7)
333 # ... and again, on all the different method's names
334 self.assertEqual(self.fi.a.__func__.known_attr, 7)
335 self.assertEqual(self.fi.a.known_attr, 7)
336
337 def test_delete___dict__(self):
338 try:
339 del self.b.__dict__
340 except (TypeError, AttributeError):
341 pass
342 else:
343 self.fail("deleting function dictionary should raise TypeError")
344
345 def test_unassigned_dict(self):
346 self.assertEqual(self.b.__dict__, {})
347
348 def test_func_as_dict_key(self):
349 value = "Some string"
350 d = {}
351 d[self.b] = value
352 self.assertEqual(d[self.b], value)
353
354
355 class FunctionDocstringTest(FuncAttrsTest):
356 def test_set_docstring_attr(self):
357 self.assertEqual(self.b.__doc__, None)
358 docstr = "A test method that does nothing"
359 self.b.__doc__ = docstr
360 self.F.a.__doc__ = docstr
361 self.assertEqual(self.b.__doc__, docstr)
362 self.assertEqual(self.fi.a.__doc__, docstr)
363 self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError)
364
365 def test_delete_docstring(self):
366 self.b.__doc__ = "The docstring"
367 del self.b.__doc__
368 self.assertEqual(self.b.__doc__, None)
369
370
371 def cell(value):
372 """Create a cell containing the given value."""
373 def f():
374 print(a)
375 a = value
376 return f.__closure__[0]
377
378 def empty_cell(empty=True):
379 """Create an empty cell."""
380 def f():
381 print(a)
382 # the intent of the following line is simply "if False:"; it's
383 # spelt this way to avoid the danger that a future optimization
384 # might simply remove an "if False:" code block.
385 if not empty:
386 a = 1729
387 return f.__closure__[0]
388
389
390 class CellTest(unittest.TestCase):
391 def test_comparison(self):
392 # These tests are here simply to exercise the comparison code;
393 # their presence should not be interpreted as providing any
394 # guarantees about the semantics (or even existence) of cell
395 # comparisons in future versions of CPython.
396 self.assertTrue(cell(2) < cell(3))
397 self.assertTrue(empty_cell() < cell('saturday'))
398 self.assertTrue(empty_cell() == empty_cell())
399 self.assertTrue(cell(-36) == cell(-36.0))
400 self.assertTrue(cell(True) > empty_cell())
401
402
403 class StaticMethodAttrsTest(unittest.TestCase):
404 def test_func_attribute(self):
405 def f():
406 pass
407
408 c = classmethod(f)
409 self.assertTrue(c.__func__ is f)
410
411 s = staticmethod(f)
412 self.assertTrue(s.__func__ is f)
413
414
415 class BuiltinFunctionPropertiesTest(unittest.TestCase):
416 # XXX Not sure where this should really go since I can't find a
417 # test module specifically for builtin_function_or_method.
418
419 def test_builtin__qualname__(self):
420 import time
421
422 # builtin function:
423 self.assertEqual(len.__qualname__, 'len')
424 self.assertEqual(time.time.__qualname__, 'time')
425
426 # builtin classmethod:
427 self.assertEqual(dict.fromkeys.__qualname__, 'dict.fromkeys')
428 self.assertEqual(float.__getformat__.__qualname__,
429 'float.__getformat__')
430
431 # builtin staticmethod:
432 self.assertEqual(str.maketrans.__qualname__, 'str.maketrans')
433 self.assertEqual(bytes.maketrans.__qualname__, 'bytes.maketrans')
434
435 # builtin bound instance method:
436 self.assertEqual([1, 2, 3].append.__qualname__, 'list.append')
437 self.assertEqual({'foo': 'bar'}.pop.__qualname__, 'dict.pop')
438
439
440 if __name__ == "__main__":
441 unittest.main()