blob: 15cf250f192a95a6bc0eaef0d773daadc340e2d9 [file] [log] [blame]
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +00001import types
Georg Brandl60d14562008-02-05 18:31:41 +00002import unittest
Barry Warsaw4a420a02001-01-15 20:30:15 +00003
Antoine Pitrou86a36b52011-11-25 18:56:07 +01004
5def global_function():
6 def inner_function():
7 class LocalClass:
8 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -04009 global inner_global_function
10 def inner_global_function():
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040011 def inner_function2():
12 pass
13 return inner_function2
Antoine Pitrou86a36b52011-11-25 18:56:07 +010014 return LocalClass
15 return lambda: inner_function
16
17
Georg Brandl60d14562008-02-05 18:31:41 +000018class FuncAttrsTest(unittest.TestCase):
19 def setUp(self):
20 class F:
21 def a(self):
22 pass
23 def b():
24 return 3
25 self.fi = F()
26 self.F = F
27 self.b = b
Barry Warsaw4a420a02001-01-15 20:30:15 +000028
Georg Brandl60d14562008-02-05 18:31:41 +000029 def cannot_set_attr(self, obj, name, value, exceptions):
30 try:
31 setattr(obj, name, value)
32 except exceptions:
33 pass
34 else:
35 self.fail("shouldn't be able to set %s to %r" % (name, value))
36 try:
37 delattr(obj, name)
38 except exceptions:
39 pass
40 else:
41 self.fail("shouldn't be able to del %s" % name)
Barry Warsaw4a420a02001-01-15 20:30:15 +000042
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +000043
Georg Brandl60d14562008-02-05 18:31:41 +000044class FunctionPropertiesTest(FuncAttrsTest):
45 # Include the external setUp method that is common to all tests
46 def test_module(self):
47 self.assertEqual(self.b.__module__, __name__)
Barry Warsaw4a420a02001-01-15 20:30:15 +000048
Georg Brandl60d14562008-02-05 18:31:41 +000049 def test_dir_includes_correct_attrs(self):
50 self.b.known_attr = 7
Benjamin Peterson577473f2010-01-19 00:09:57 +000051 self.assertIn('known_attr', dir(self.b),
Georg Brandl60d14562008-02-05 18:31:41 +000052 "set attributes not in dir listing of method")
53 # Test on underlying function object of method
54 self.F.a.known_attr = 7
Benjamin Peterson577473f2010-01-19 00:09:57 +000055 self.assertIn('known_attr', dir(self.fi.a), "set attribute on function "
Georg Brandl60d14562008-02-05 18:31:41 +000056 "implementations, should show up in next dir")
Barry Warsawc1e100f2001-02-26 18:07:26 +000057
Georg Brandl60d14562008-02-05 18:31:41 +000058 def test_duplicate_function_equality(self):
59 # Body of `duplicate' is the exact same as self.b
60 def duplicate():
61 'my docstring'
62 return 3
63 self.assertNotEqual(self.b, duplicate)
Barry Warsaw4a420a02001-01-15 20:30:15 +000064
Georg Brandl60d14562008-02-05 18:31:41 +000065 def test_copying___code__(self):
66 def test(): pass
67 self.assertEqual(test(), None)
68 test.__code__ = self.b.__code__
69 self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily
Barry Warsaw4a420a02001-01-15 20:30:15 +000070
Georg Brandl60d14562008-02-05 18:31:41 +000071 def test___globals__(self):
Georg Brandl4cb97d02009-09-04 11:20:54 +000072 self.assertIs(self.b.__globals__, globals())
73 self.cannot_set_attr(self.b, '__globals__', 2,
74 (AttributeError, TypeError))
75
Victor Stinnera3c3ffa2021-02-18 12:35:37 +010076 def test___builtins__(self):
77 self.assertIs(self.b.__builtins__, __builtins__)
78 self.cannot_set_attr(self.b, '__builtins__', 2,
79 (AttributeError, TypeError))
80
Georg Brandl4cb97d02009-09-04 11:20:54 +000081 def test___closure__(self):
82 a = 12
83 def f(): print(a)
84 c = f.__closure__
Ezio Melottie9615932010-01-24 19:26:24 +000085 self.assertIsInstance(c, tuple)
Georg Brandl4cb97d02009-09-04 11:20:54 +000086 self.assertEqual(len(c), 1)
87 # don't have a type object handy
88 self.assertEqual(c[0].__class__.__name__, "cell")
89 self.cannot_set_attr(f, "__closure__", c, AttributeError)
90
Pierre Glaserdf8d2cd2019-02-07 20:36:48 +010091 def test_cell_new(self):
92 cell_obj = types.CellType(1)
93 self.assertEqual(cell_obj.cell_contents, 1)
94
95 cell_obj = types.CellType()
96 msg = "shouldn't be able to read an empty cell"
97 with self.assertRaises(ValueError, msg=msg):
98 cell_obj.cell_contents
99
Georg Brandl4cb97d02009-09-04 11:20:54 +0000100 def test_empty_cell(self):
101 def f(): print(a)
102 try:
103 f.__closure__[0].cell_contents
104 except ValueError:
105 pass
106 else:
107 self.fail("shouldn't be able to read an empty cell")
108 a = 12
Barry Warsaw4a420a02001-01-15 20:30:15 +0000109
Lisa Roach64505a12017-06-08 04:43:26 -0700110 def test_set_cell(self):
111 a = 12
112 def f(): return a
113 c = f.__closure__
114 c[0].cell_contents = 9
115 self.assertEqual(c[0].cell_contents, 9)
116 self.assertEqual(f(), 9)
117 self.assertEqual(a, 9)
118 del c[0].cell_contents
119 try:
120 c[0].cell_contents
121 except ValueError:
122 pass
123 else:
124 self.fail("shouldn't be able to read an empty cell")
125 with self.assertRaises(NameError):
126 f()
127 with self.assertRaises(UnboundLocalError):
128 print(a)
129
Georg Brandl60d14562008-02-05 18:31:41 +0000130 def test___name__(self):
131 self.assertEqual(self.b.__name__, 'b')
132 self.b.__name__ = 'c'
133 self.assertEqual(self.b.__name__, 'c')
134 self.b.__name__ = 'd'
135 self.assertEqual(self.b.__name__, 'd')
136 # __name__ and __name__ must be a string
137 self.cannot_set_attr(self.b, '__name__', 7, TypeError)
138 # __name__ must be available when in restricted mode. Exec will raise
139 # AttributeError if __name__ is not available on f.
140 s = """def f(): pass\nf.__name__"""
141 exec(s, {'__builtins__': {}})
142 # Test on methods, too
143 self.assertEqual(self.fi.a.__name__, 'a')
144 self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000145
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100146 def test___qualname__(self):
147 # PEP 3155
148 self.assertEqual(self.b.__qualname__, 'FuncAttrsTest.setUp.<locals>.b')
149 self.assertEqual(FuncAttrsTest.setUp.__qualname__, 'FuncAttrsTest.setUp')
150 self.assertEqual(global_function.__qualname__, 'global_function')
151 self.assertEqual(global_function().__qualname__,
152 'global_function.<locals>.<lambda>')
153 self.assertEqual(global_function()().__qualname__,
154 'global_function.<locals>.inner_function')
155 self.assertEqual(global_function()()().__qualname__,
156 'global_function.<locals>.inner_function.<locals>.LocalClass')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400157 self.assertEqual(inner_global_function.__qualname__, 'inner_global_function')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400158 self.assertEqual(inner_global_function().__qualname__, 'inner_global_function.<locals>.inner_function2')
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100159 self.b.__qualname__ = 'c'
160 self.assertEqual(self.b.__qualname__, 'c')
161 self.b.__qualname__ = 'd'
162 self.assertEqual(self.b.__qualname__, 'd')
163 # __qualname__ must be a string
164 self.cannot_set_attr(self.b, '__qualname__', 7, TypeError)
165
Georg Brandl60d14562008-02-05 18:31:41 +0000166 def test___code__(self):
167 num_one, num_two = 7, 8
168 def a(): pass
169 def b(): return 12
170 def c(): return num_one
171 def d(): return num_two
172 def e(): return num_one, num_two
173 for func in [a, b, c, d, e]:
174 self.assertEqual(type(func.__code__), types.CodeType)
175 self.assertEqual(c(), 7)
176 self.assertEqual(d(), 8)
177 d.__code__ = c.__code__
178 self.assertEqual(c.__code__, d.__code__)
179 self.assertEqual(c(), 7)
180 # self.assertEqual(d(), 7)
Georg Brandl4cb97d02009-09-04 11:20:54 +0000181 try:
182 b.__code__ = c.__code__
183 except ValueError:
184 pass
185 else:
186 self.fail("__code__ with different numbers of free vars should "
187 "not be possible")
188 try:
189 e.__code__ = d.__code__
190 except ValueError:
191 pass
192 else:
193 self.fail("__code__ with different numbers of free vars should "
194 "not be possible")
Barry Warsawc1e100f2001-02-26 18:07:26 +0000195
Georg Brandl60d14562008-02-05 18:31:41 +0000196 def test_blank_func_defaults(self):
197 self.assertEqual(self.b.__defaults__, None)
198 del self.b.__defaults__
199 self.assertEqual(self.b.__defaults__, None)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000200
Georg Brandl60d14562008-02-05 18:31:41 +0000201 def test_func_default_args(self):
202 def first_func(a, b):
203 return a+b
204 def second_func(a=1, b=2):
205 return a+b
206 self.assertEqual(first_func.__defaults__, None)
207 self.assertEqual(second_func.__defaults__, (1, 2))
208 first_func.__defaults__ = (1, 2)
209 self.assertEqual(first_func.__defaults__, (1, 2))
210 self.assertEqual(first_func(), 3)
211 self.assertEqual(first_func(3), 5)
212 self.assertEqual(first_func(3, 5), 8)
213 del second_func.__defaults__
214 self.assertEqual(second_func.__defaults__, None)
Georg Brandl4cb97d02009-09-04 11:20:54 +0000215 try:
216 second_func()
217 except TypeError:
218 pass
219 else:
220 self.fail("__defaults__ does not update; deleting it does not "
221 "remove requirement")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000222
Georg Brandl4cb97d02009-09-04 11:20:54 +0000223
224class InstancemethodAttrTest(FuncAttrsTest):
Barry Warsaw4a420a02001-01-15 20:30:15 +0000225
Georg Brandl60d14562008-02-05 18:31:41 +0000226 def test___class__(self):
227 self.assertEqual(self.fi.a.__self__.__class__, self.F)
228 self.cannot_set_attr(self.fi.a, "__class__", self.F, TypeError)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000229
Georg Brandl60d14562008-02-05 18:31:41 +0000230 def test___func__(self):
231 self.assertEqual(self.fi.a.__func__, self.F.a)
232 self.cannot_set_attr(self.fi.a, "__func__", self.F.a, AttributeError)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000233
Georg Brandl60d14562008-02-05 18:31:41 +0000234 def test___self__(self):
235 self.assertEqual(self.fi.a.__self__, self.fi)
236 self.cannot_set_attr(self.fi.a, "__self__", self.fi, AttributeError)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000237
Georg Brandl60d14562008-02-05 18:31:41 +0000238 def test___func___non_method(self):
239 # Behavior should be the same when a method is added via an attr
240 # assignment
241 self.fi.id = types.MethodType(id, self.fi)
242 self.assertEqual(self.fi.id(), id(self.fi))
243 # Test usage
Georg Brandl4cb97d02009-09-04 11:20:54 +0000244 try:
245 self.fi.id.unknown_attr
246 except AttributeError:
247 pass
248 else:
249 self.fail("using unknown attributes should raise AttributeError")
Georg Brandl60d14562008-02-05 18:31:41 +0000250 # Test assignment and deletion
251 self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000252
Georg Brandl4cb97d02009-09-04 11:20:54 +0000253
Georg Brandl60d14562008-02-05 18:31:41 +0000254class ArbitraryFunctionAttrTest(FuncAttrsTest):
255 def test_set_attr(self):
256 self.b.known_attr = 7
257 self.assertEqual(self.b.known_attr, 7)
Georg Brandl4cb97d02009-09-04 11:20:54 +0000258 try:
259 self.fi.a.known_attr = 7
260 except AttributeError:
261 pass
262 else:
263 self.fail("setting attributes on methods should raise error")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000264
Georg Brandl60d14562008-02-05 18:31:41 +0000265 def test_delete_unknown_attr(self):
Georg Brandl4cb97d02009-09-04 11:20:54 +0000266 try:
267 del self.b.unknown_attr
268 except AttributeError:
269 pass
270 else:
271 self.fail("deleting unknown attribute should raise TypeError")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000272
Georg Brandl60d14562008-02-05 18:31:41 +0000273 def test_unset_attr(self):
274 for func in [self.b, self.fi.a]:
Georg Brandl4cb97d02009-09-04 11:20:54 +0000275 try:
276 func.non_existent_attr
277 except AttributeError:
278 pass
279 else:
280 self.fail("using unknown attributes should raise "
281 "AttributeError")
282
Barry Warsaw4a420a02001-01-15 20:30:15 +0000283
Georg Brandl60d14562008-02-05 18:31:41 +0000284class FunctionDictsTest(FuncAttrsTest):
285 def test_setting_dict_to_invalid(self):
286 self.cannot_set_attr(self.b, '__dict__', None, TypeError)
Raymond Hettingerf80680d2008-02-06 00:07:11 +0000287 from collections import UserDict
Georg Brandl60d14562008-02-05 18:31:41 +0000288 d = UserDict({'known_attr': 7})
289 self.cannot_set_attr(self.fi.a.__func__, '__dict__', d, TypeError)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000290
Georg Brandl60d14562008-02-05 18:31:41 +0000291 def test_setting_dict_to_valid(self):
292 d = {'known_attr': 7}
293 self.b.__dict__ = d
294 # Test assignment
Georg Brandl4cb97d02009-09-04 11:20:54 +0000295 self.assertIs(d, self.b.__dict__)
Georg Brandl60d14562008-02-05 18:31:41 +0000296 # ... and on all the different ways of referencing the method's func
297 self.F.a.__dict__ = d
Georg Brandl4cb97d02009-09-04 11:20:54 +0000298 self.assertIs(d, self.fi.a.__func__.__dict__)
299 self.assertIs(d, self.fi.a.__dict__)
Georg Brandl60d14562008-02-05 18:31:41 +0000300 # Test value
301 self.assertEqual(self.b.known_attr, 7)
302 self.assertEqual(self.b.__dict__['known_attr'], 7)
303 # ... and again, on all the different method's names
304 self.assertEqual(self.fi.a.__func__.known_attr, 7)
305 self.assertEqual(self.fi.a.known_attr, 7)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000306
Georg Brandl60d14562008-02-05 18:31:41 +0000307 def test_delete___dict__(self):
Georg Brandl4cb97d02009-09-04 11:20:54 +0000308 try:
309 del self.b.__dict__
310 except TypeError:
311 pass
312 else:
313 self.fail("deleting function dictionary should raise TypeError")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000314
Georg Brandl60d14562008-02-05 18:31:41 +0000315 def test_unassigned_dict(self):
316 self.assertEqual(self.b.__dict__, {})
Barry Warsaw4a420a02001-01-15 20:30:15 +0000317
Georg Brandl60d14562008-02-05 18:31:41 +0000318 def test_func_as_dict_key(self):
319 value = "Some string"
320 d = {}
321 d[self.b] = value
322 self.assertEqual(d[self.b], value)
Barry Warsaw534c60f2001-01-15 21:00:02 +0000323
Georg Brandl4cb97d02009-09-04 11:20:54 +0000324
Georg Brandl60d14562008-02-05 18:31:41 +0000325class FunctionDocstringTest(FuncAttrsTest):
326 def test_set_docstring_attr(self):
327 self.assertEqual(self.b.__doc__, None)
328 docstr = "A test method that does nothing"
329 self.b.__doc__ = docstr
330 self.F.a.__doc__ = docstr
331 self.assertEqual(self.b.__doc__, docstr)
332 self.assertEqual(self.fi.a.__doc__, docstr)
333 self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError)
Guido van Rossumbd131492001-09-18 03:28:54 +0000334
Georg Brandl60d14562008-02-05 18:31:41 +0000335 def test_delete_docstring(self):
336 self.b.__doc__ = "The docstring"
337 del self.b.__doc__
338 self.assertEqual(self.b.__doc__, None)
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000339
Georg Brandl4cb97d02009-09-04 11:20:54 +0000340
Mark Dickinson211c6252009-02-01 10:28:51 +0000341def cell(value):
342 """Create a cell containing the given value."""
343 def f():
344 print(a)
345 a = value
346 return f.__closure__[0]
347
348def empty_cell(empty=True):
349 """Create an empty cell."""
350 def f():
351 print(a)
352 # the intent of the following line is simply "if False:"; it's
353 # spelt this way to avoid the danger that a future optimization
354 # might simply remove an "if False:" code block.
355 if not empty:
356 a = 1729
357 return f.__closure__[0]
358
Georg Brandl4cb97d02009-09-04 11:20:54 +0000359
Mark Dickinson211c6252009-02-01 10:28:51 +0000360class CellTest(unittest.TestCase):
361 def test_comparison(self):
362 # These tests are here simply to exercise the comparison code;
363 # their presence should not be interpreted as providing any
364 # guarantees about the semantics (or even existence) of cell
365 # comparisons in future versions of CPython.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000366 self.assertTrue(cell(2) < cell(3))
367 self.assertTrue(empty_cell() < cell('saturday'))
368 self.assertTrue(empty_cell() == empty_cell())
369 self.assertTrue(cell(-36) == cell(-36.0))
370 self.assertTrue(cell(True) > empty_cell())
Mark Dickinson211c6252009-02-01 10:28:51 +0000371
Georg Brandl4cb97d02009-09-04 11:20:54 +0000372
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000373class StaticMethodAttrsTest(unittest.TestCase):
374 def test_func_attribute(self):
375 def f():
376 pass
377
378 c = classmethod(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000379 self.assertTrue(c.__func__ is f)
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000380
381 s = staticmethod(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000382 self.assertTrue(s.__func__ is f)
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000383
Mark Dickinson211c6252009-02-01 10:28:51 +0000384
Antoine Pitrou5b629422011-12-23 12:40:16 +0100385class BuiltinFunctionPropertiesTest(unittest.TestCase):
386 # XXX Not sure where this should really go since I can't find a
387 # test module specifically for builtin_function_or_method.
388
389 def test_builtin__qualname__(self):
390 import time
391
392 # builtin function:
393 self.assertEqual(len.__qualname__, 'len')
394 self.assertEqual(time.time.__qualname__, 'time')
395
396 # builtin classmethod:
397 self.assertEqual(dict.fromkeys.__qualname__, 'dict.fromkeys')
398 self.assertEqual(float.__getformat__.__qualname__,
399 'float.__getformat__')
400
401 # builtin staticmethod:
402 self.assertEqual(str.maketrans.__qualname__, 'str.maketrans')
403 self.assertEqual(bytes.maketrans.__qualname__, 'bytes.maketrans')
404
405 # builtin bound instance method:
406 self.assertEqual([1, 2, 3].append.__qualname__, 'list.append')
407 self.assertEqual({'foo': 'bar'}.pop.__qualname__, 'dict.pop')
408
409
Georg Brandl60d14562008-02-05 18:31:41 +0000410if __name__ == "__main__":
Zachary Ware38c707e2015-04-13 15:00:43 -0500411 unittest.main()