blob: 5094f7ba1f04dbbc82c4fc5084791f8b7ce27a4c [file] [log] [blame]
Benjamin Petersonee8712c2008-05-20 21:35:26 +00001from test import support
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +00002import types
Georg Brandl60d14562008-02-05 18:31:41 +00003import unittest
Barry Warsaw4a420a02001-01-15 20:30:15 +00004
Antoine Pitrou86a36b52011-11-25 18:56:07 +01005
6def global_function():
7 def inner_function():
8 class LocalClass:
9 pass
Benjamin Peterson3d9e4812013-10-19 16:01:13 -040010 global inner_global_function
11 def inner_global_function():
Benjamin Peterson6b4f7802013-10-20 17:50:28 -040012 def inner_function2():
13 pass
14 return inner_function2
Antoine Pitrou86a36b52011-11-25 18:56:07 +010015 return LocalClass
16 return lambda: inner_function
17
18
Georg Brandl60d14562008-02-05 18:31:41 +000019class FuncAttrsTest(unittest.TestCase):
20 def setUp(self):
21 class F:
22 def a(self):
23 pass
24 def b():
25 return 3
26 self.fi = F()
27 self.F = F
28 self.b = b
Barry Warsaw4a420a02001-01-15 20:30:15 +000029
Georg Brandl60d14562008-02-05 18:31:41 +000030 def cannot_set_attr(self, obj, name, value, exceptions):
31 try:
32 setattr(obj, name, value)
33 except exceptions:
34 pass
35 else:
36 self.fail("shouldn't be able to set %s to %r" % (name, value))
37 try:
38 delattr(obj, name)
39 except exceptions:
40 pass
41 else:
42 self.fail("shouldn't be able to del %s" % name)
Barry Warsaw4a420a02001-01-15 20:30:15 +000043
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +000044
Georg Brandl60d14562008-02-05 18:31:41 +000045class FunctionPropertiesTest(FuncAttrsTest):
46 # Include the external setUp method that is common to all tests
47 def test_module(self):
48 self.assertEqual(self.b.__module__, __name__)
Barry Warsaw4a420a02001-01-15 20:30:15 +000049
Georg Brandl60d14562008-02-05 18:31:41 +000050 def test_dir_includes_correct_attrs(self):
51 self.b.known_attr = 7
Benjamin Peterson577473f2010-01-19 00:09:57 +000052 self.assertIn('known_attr', dir(self.b),
Georg Brandl60d14562008-02-05 18:31:41 +000053 "set attributes not in dir listing of method")
54 # Test on underlying function object of method
55 self.F.a.known_attr = 7
Benjamin Peterson577473f2010-01-19 00:09:57 +000056 self.assertIn('known_attr', dir(self.fi.a), "set attribute on function "
Georg Brandl60d14562008-02-05 18:31:41 +000057 "implementations, should show up in next dir")
Barry Warsawc1e100f2001-02-26 18:07:26 +000058
Georg Brandl60d14562008-02-05 18:31:41 +000059 def test_duplicate_function_equality(self):
60 # Body of `duplicate' is the exact same as self.b
61 def duplicate():
62 'my docstring'
63 return 3
64 self.assertNotEqual(self.b, duplicate)
Barry Warsaw4a420a02001-01-15 20:30:15 +000065
Georg Brandl60d14562008-02-05 18:31:41 +000066 def test_copying___code__(self):
67 def test(): pass
68 self.assertEqual(test(), None)
69 test.__code__ = self.b.__code__
70 self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily
Barry Warsaw4a420a02001-01-15 20:30:15 +000071
Georg Brandl60d14562008-02-05 18:31:41 +000072 def test___globals__(self):
Georg Brandl4cb97d02009-09-04 11:20:54 +000073 self.assertIs(self.b.__globals__, globals())
74 self.cannot_set_attr(self.b, '__globals__', 2,
75 (AttributeError, TypeError))
76
77 def test___closure__(self):
78 a = 12
79 def f(): print(a)
80 c = f.__closure__
Ezio Melottie9615932010-01-24 19:26:24 +000081 self.assertIsInstance(c, tuple)
Georg Brandl4cb97d02009-09-04 11:20:54 +000082 self.assertEqual(len(c), 1)
83 # don't have a type object handy
84 self.assertEqual(c[0].__class__.__name__, "cell")
85 self.cannot_set_attr(f, "__closure__", c, AttributeError)
86
87 def test_empty_cell(self):
88 def f(): print(a)
89 try:
90 f.__closure__[0].cell_contents
91 except ValueError:
92 pass
93 else:
94 self.fail("shouldn't be able to read an empty cell")
95 a = 12
Barry Warsaw4a420a02001-01-15 20:30:15 +000096
Georg Brandl60d14562008-02-05 18:31:41 +000097 def test___name__(self):
98 self.assertEqual(self.b.__name__, 'b')
99 self.b.__name__ = 'c'
100 self.assertEqual(self.b.__name__, 'c')
101 self.b.__name__ = 'd'
102 self.assertEqual(self.b.__name__, 'd')
103 # __name__ and __name__ must be a string
104 self.cannot_set_attr(self.b, '__name__', 7, TypeError)
105 # __name__ must be available when in restricted mode. Exec will raise
106 # AttributeError if __name__ is not available on f.
107 s = """def f(): pass\nf.__name__"""
108 exec(s, {'__builtins__': {}})
109 # Test on methods, too
110 self.assertEqual(self.fi.a.__name__, 'a')
111 self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000112
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100113 def test___qualname__(self):
114 # PEP 3155
115 self.assertEqual(self.b.__qualname__, 'FuncAttrsTest.setUp.<locals>.b')
116 self.assertEqual(FuncAttrsTest.setUp.__qualname__, 'FuncAttrsTest.setUp')
117 self.assertEqual(global_function.__qualname__, 'global_function')
118 self.assertEqual(global_function().__qualname__,
119 'global_function.<locals>.<lambda>')
120 self.assertEqual(global_function()().__qualname__,
121 'global_function.<locals>.inner_function')
122 self.assertEqual(global_function()()().__qualname__,
123 'global_function.<locals>.inner_function.<locals>.LocalClass')
Benjamin Peterson3d9e4812013-10-19 16:01:13 -0400124 self.assertEqual(inner_global_function.__qualname__, 'inner_global_function')
Benjamin Peterson6b4f7802013-10-20 17:50:28 -0400125 self.assertEqual(inner_global_function().__qualname__, 'inner_global_function.<locals>.inner_function2')
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100126 self.b.__qualname__ = 'c'
127 self.assertEqual(self.b.__qualname__, 'c')
128 self.b.__qualname__ = 'd'
129 self.assertEqual(self.b.__qualname__, 'd')
130 # __qualname__ must be a string
131 self.cannot_set_attr(self.b, '__qualname__', 7, TypeError)
132
Georg Brandl60d14562008-02-05 18:31:41 +0000133 def test___code__(self):
134 num_one, num_two = 7, 8
135 def a(): pass
136 def b(): return 12
137 def c(): return num_one
138 def d(): return num_two
139 def e(): return num_one, num_two
140 for func in [a, b, c, d, e]:
141 self.assertEqual(type(func.__code__), types.CodeType)
142 self.assertEqual(c(), 7)
143 self.assertEqual(d(), 8)
144 d.__code__ = c.__code__
145 self.assertEqual(c.__code__, d.__code__)
146 self.assertEqual(c(), 7)
147 # self.assertEqual(d(), 7)
Georg Brandl4cb97d02009-09-04 11:20:54 +0000148 try:
149 b.__code__ = c.__code__
150 except ValueError:
151 pass
152 else:
153 self.fail("__code__ with different numbers of free vars should "
154 "not be possible")
155 try:
156 e.__code__ = d.__code__
157 except ValueError:
158 pass
159 else:
160 self.fail("__code__ with different numbers of free vars should "
161 "not be possible")
Barry Warsawc1e100f2001-02-26 18:07:26 +0000162
Georg Brandl60d14562008-02-05 18:31:41 +0000163 def test_blank_func_defaults(self):
164 self.assertEqual(self.b.__defaults__, None)
165 del self.b.__defaults__
166 self.assertEqual(self.b.__defaults__, None)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000167
Georg Brandl60d14562008-02-05 18:31:41 +0000168 def test_func_default_args(self):
169 def first_func(a, b):
170 return a+b
171 def second_func(a=1, b=2):
172 return a+b
173 self.assertEqual(first_func.__defaults__, None)
174 self.assertEqual(second_func.__defaults__, (1, 2))
175 first_func.__defaults__ = (1, 2)
176 self.assertEqual(first_func.__defaults__, (1, 2))
177 self.assertEqual(first_func(), 3)
178 self.assertEqual(first_func(3), 5)
179 self.assertEqual(first_func(3, 5), 8)
180 del second_func.__defaults__
181 self.assertEqual(second_func.__defaults__, None)
Georg Brandl4cb97d02009-09-04 11:20:54 +0000182 try:
183 second_func()
184 except TypeError:
185 pass
186 else:
187 self.fail("__defaults__ does not update; deleting it does not "
188 "remove requirement")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000189
Georg Brandl4cb97d02009-09-04 11:20:54 +0000190
191class InstancemethodAttrTest(FuncAttrsTest):
Barry Warsaw4a420a02001-01-15 20:30:15 +0000192
Georg Brandl60d14562008-02-05 18:31:41 +0000193 def test___class__(self):
194 self.assertEqual(self.fi.a.__self__.__class__, self.F)
195 self.cannot_set_attr(self.fi.a, "__class__", self.F, TypeError)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000196
Georg Brandl60d14562008-02-05 18:31:41 +0000197 def test___func__(self):
198 self.assertEqual(self.fi.a.__func__, self.F.a)
199 self.cannot_set_attr(self.fi.a, "__func__", self.F.a, AttributeError)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000200
Georg Brandl60d14562008-02-05 18:31:41 +0000201 def test___self__(self):
202 self.assertEqual(self.fi.a.__self__, self.fi)
203 self.cannot_set_attr(self.fi.a, "__self__", self.fi, AttributeError)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000204
Georg Brandl60d14562008-02-05 18:31:41 +0000205 def test___func___non_method(self):
206 # Behavior should be the same when a method is added via an attr
207 # assignment
208 self.fi.id = types.MethodType(id, self.fi)
209 self.assertEqual(self.fi.id(), id(self.fi))
210 # Test usage
Georg Brandl4cb97d02009-09-04 11:20:54 +0000211 try:
212 self.fi.id.unknown_attr
213 except AttributeError:
214 pass
215 else:
216 self.fail("using unknown attributes should raise AttributeError")
Georg Brandl60d14562008-02-05 18:31:41 +0000217 # Test assignment and deletion
218 self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000219
Georg Brandl4cb97d02009-09-04 11:20:54 +0000220
Georg Brandl60d14562008-02-05 18:31:41 +0000221class ArbitraryFunctionAttrTest(FuncAttrsTest):
222 def test_set_attr(self):
223 self.b.known_attr = 7
224 self.assertEqual(self.b.known_attr, 7)
Georg Brandl4cb97d02009-09-04 11:20:54 +0000225 try:
226 self.fi.a.known_attr = 7
227 except AttributeError:
228 pass
229 else:
230 self.fail("setting attributes on methods should raise error")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000231
Georg Brandl60d14562008-02-05 18:31:41 +0000232 def test_delete_unknown_attr(self):
Georg Brandl4cb97d02009-09-04 11:20:54 +0000233 try:
234 del self.b.unknown_attr
235 except AttributeError:
236 pass
237 else:
238 self.fail("deleting unknown attribute should raise TypeError")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000239
Georg Brandl60d14562008-02-05 18:31:41 +0000240 def test_unset_attr(self):
241 for func in [self.b, self.fi.a]:
Georg Brandl4cb97d02009-09-04 11:20:54 +0000242 try:
243 func.non_existent_attr
244 except AttributeError:
245 pass
246 else:
247 self.fail("using unknown attributes should raise "
248 "AttributeError")
249
Barry Warsaw4a420a02001-01-15 20:30:15 +0000250
Georg Brandl60d14562008-02-05 18:31:41 +0000251class FunctionDictsTest(FuncAttrsTest):
252 def test_setting_dict_to_invalid(self):
253 self.cannot_set_attr(self.b, '__dict__', None, TypeError)
Raymond Hettingerf80680d2008-02-06 00:07:11 +0000254 from collections import UserDict
Georg Brandl60d14562008-02-05 18:31:41 +0000255 d = UserDict({'known_attr': 7})
256 self.cannot_set_attr(self.fi.a.__func__, '__dict__', d, TypeError)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000257
Georg Brandl60d14562008-02-05 18:31:41 +0000258 def test_setting_dict_to_valid(self):
259 d = {'known_attr': 7}
260 self.b.__dict__ = d
261 # Test assignment
Georg Brandl4cb97d02009-09-04 11:20:54 +0000262 self.assertIs(d, self.b.__dict__)
Georg Brandl60d14562008-02-05 18:31:41 +0000263 # ... and on all the different ways of referencing the method's func
264 self.F.a.__dict__ = d
Georg Brandl4cb97d02009-09-04 11:20:54 +0000265 self.assertIs(d, self.fi.a.__func__.__dict__)
266 self.assertIs(d, self.fi.a.__dict__)
Georg Brandl60d14562008-02-05 18:31:41 +0000267 # Test value
268 self.assertEqual(self.b.known_attr, 7)
269 self.assertEqual(self.b.__dict__['known_attr'], 7)
270 # ... and again, on all the different method's names
271 self.assertEqual(self.fi.a.__func__.known_attr, 7)
272 self.assertEqual(self.fi.a.known_attr, 7)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000273
Georg Brandl60d14562008-02-05 18:31:41 +0000274 def test_delete___dict__(self):
Georg Brandl4cb97d02009-09-04 11:20:54 +0000275 try:
276 del self.b.__dict__
277 except TypeError:
278 pass
279 else:
280 self.fail("deleting function dictionary should raise TypeError")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000281
Georg Brandl60d14562008-02-05 18:31:41 +0000282 def test_unassigned_dict(self):
283 self.assertEqual(self.b.__dict__, {})
Barry Warsaw4a420a02001-01-15 20:30:15 +0000284
Georg Brandl60d14562008-02-05 18:31:41 +0000285 def test_func_as_dict_key(self):
286 value = "Some string"
287 d = {}
288 d[self.b] = value
289 self.assertEqual(d[self.b], value)
Barry Warsaw534c60f2001-01-15 21:00:02 +0000290
Georg Brandl4cb97d02009-09-04 11:20:54 +0000291
Georg Brandl60d14562008-02-05 18:31:41 +0000292class FunctionDocstringTest(FuncAttrsTest):
293 def test_set_docstring_attr(self):
294 self.assertEqual(self.b.__doc__, None)
295 docstr = "A test method that does nothing"
296 self.b.__doc__ = docstr
297 self.F.a.__doc__ = docstr
298 self.assertEqual(self.b.__doc__, docstr)
299 self.assertEqual(self.fi.a.__doc__, docstr)
300 self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError)
Guido van Rossumbd131492001-09-18 03:28:54 +0000301
Georg Brandl60d14562008-02-05 18:31:41 +0000302 def test_delete_docstring(self):
303 self.b.__doc__ = "The docstring"
304 del self.b.__doc__
305 self.assertEqual(self.b.__doc__, None)
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000306
Georg Brandl4cb97d02009-09-04 11:20:54 +0000307
Mark Dickinson211c6252009-02-01 10:28:51 +0000308def cell(value):
309 """Create a cell containing the given value."""
310 def f():
311 print(a)
312 a = value
313 return f.__closure__[0]
314
315def empty_cell(empty=True):
316 """Create an empty cell."""
317 def f():
318 print(a)
319 # the intent of the following line is simply "if False:"; it's
320 # spelt this way to avoid the danger that a future optimization
321 # might simply remove an "if False:" code block.
322 if not empty:
323 a = 1729
324 return f.__closure__[0]
325
Georg Brandl4cb97d02009-09-04 11:20:54 +0000326
Mark Dickinson211c6252009-02-01 10:28:51 +0000327class CellTest(unittest.TestCase):
328 def test_comparison(self):
329 # These tests are here simply to exercise the comparison code;
330 # their presence should not be interpreted as providing any
331 # guarantees about the semantics (or even existence) of cell
332 # comparisons in future versions of CPython.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000333 self.assertTrue(cell(2) < cell(3))
334 self.assertTrue(empty_cell() < cell('saturday'))
335 self.assertTrue(empty_cell() == empty_cell())
336 self.assertTrue(cell(-36) == cell(-36.0))
337 self.assertTrue(cell(True) > empty_cell())
Mark Dickinson211c6252009-02-01 10:28:51 +0000338
Georg Brandl4cb97d02009-09-04 11:20:54 +0000339
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000340class StaticMethodAttrsTest(unittest.TestCase):
341 def test_func_attribute(self):
342 def f():
343 pass
344
345 c = classmethod(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000346 self.assertTrue(c.__func__ is f)
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000347
348 s = staticmethod(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000349 self.assertTrue(s.__func__ is f)
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000350
Mark Dickinson211c6252009-02-01 10:28:51 +0000351
Antoine Pitrou5b629422011-12-23 12:40:16 +0100352class BuiltinFunctionPropertiesTest(unittest.TestCase):
353 # XXX Not sure where this should really go since I can't find a
354 # test module specifically for builtin_function_or_method.
355
356 def test_builtin__qualname__(self):
357 import time
358
359 # builtin function:
360 self.assertEqual(len.__qualname__, 'len')
361 self.assertEqual(time.time.__qualname__, 'time')
362
363 # builtin classmethod:
364 self.assertEqual(dict.fromkeys.__qualname__, 'dict.fromkeys')
365 self.assertEqual(float.__getformat__.__qualname__,
366 'float.__getformat__')
367
368 # builtin staticmethod:
369 self.assertEqual(str.maketrans.__qualname__, 'str.maketrans')
370 self.assertEqual(bytes.maketrans.__qualname__, 'bytes.maketrans')
371
372 # builtin bound instance method:
373 self.assertEqual([1, 2, 3].append.__qualname__, 'list.append')
374 self.assertEqual({'foo': 'bar'}.pop.__qualname__, 'dict.pop')
375
376
Georg Brandl60d14562008-02-05 18:31:41 +0000377def test_main():
Georg Brandl4cb97d02009-09-04 11:20:54 +0000378 support.run_unittest(FunctionPropertiesTest, InstancemethodAttrTest,
Georg Brandl60d14562008-02-05 18:31:41 +0000379 ArbitraryFunctionAttrTest, FunctionDictsTest,
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000380 FunctionDocstringTest, CellTest,
Antoine Pitrou5b629422011-12-23 12:40:16 +0100381 StaticMethodAttrsTest,
382 BuiltinFunctionPropertiesTest)
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000383
Georg Brandl60d14562008-02-05 18:31:41 +0000384if __name__ == "__main__":
385 test_main()