blob: c8ed83020edac68e10cdf3f073942bf33a739e40 [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
10 return LocalClass
11 return lambda: inner_function
12
13
Georg Brandl60d14562008-02-05 18:31:41 +000014class FuncAttrsTest(unittest.TestCase):
15 def setUp(self):
16 class F:
17 def a(self):
18 pass
19 def b():
20 return 3
21 self.fi = F()
22 self.F = F
23 self.b = b
Barry Warsaw4a420a02001-01-15 20:30:15 +000024
Georg Brandl60d14562008-02-05 18:31:41 +000025 def cannot_set_attr(self, obj, name, value, exceptions):
26 try:
27 setattr(obj, name, value)
28 except exceptions:
29 pass
30 else:
31 self.fail("shouldn't be able to set %s to %r" % (name, value))
32 try:
33 delattr(obj, name)
34 except exceptions:
35 pass
36 else:
37 self.fail("shouldn't be able to del %s" % name)
Barry Warsaw4a420a02001-01-15 20:30:15 +000038
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +000039
Georg Brandl60d14562008-02-05 18:31:41 +000040class FunctionPropertiesTest(FuncAttrsTest):
41 # Include the external setUp method that is common to all tests
42 def test_module(self):
43 self.assertEqual(self.b.__module__, __name__)
Barry Warsaw4a420a02001-01-15 20:30:15 +000044
Georg Brandl60d14562008-02-05 18:31:41 +000045 def test_dir_includes_correct_attrs(self):
46 self.b.known_attr = 7
Benjamin Peterson577473f2010-01-19 00:09:57 +000047 self.assertIn('known_attr', dir(self.b),
Georg Brandl60d14562008-02-05 18:31:41 +000048 "set attributes not in dir listing of method")
49 # Test on underlying function object of method
50 self.F.a.known_attr = 7
Benjamin Peterson577473f2010-01-19 00:09:57 +000051 self.assertIn('known_attr', dir(self.fi.a), "set attribute on function "
Georg Brandl60d14562008-02-05 18:31:41 +000052 "implementations, should show up in next dir")
Barry Warsawc1e100f2001-02-26 18:07:26 +000053
Georg Brandl60d14562008-02-05 18:31:41 +000054 def test_duplicate_function_equality(self):
55 # Body of `duplicate' is the exact same as self.b
56 def duplicate():
57 'my docstring'
58 return 3
59 self.assertNotEqual(self.b, duplicate)
Barry Warsaw4a420a02001-01-15 20:30:15 +000060
Georg Brandl60d14562008-02-05 18:31:41 +000061 def test_copying___code__(self):
62 def test(): pass
63 self.assertEqual(test(), None)
64 test.__code__ = self.b.__code__
65 self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily
Barry Warsaw4a420a02001-01-15 20:30:15 +000066
Georg Brandl60d14562008-02-05 18:31:41 +000067 def test___globals__(self):
Georg Brandl4cb97d02009-09-04 11:20:54 +000068 self.assertIs(self.b.__globals__, globals())
69 self.cannot_set_attr(self.b, '__globals__', 2,
70 (AttributeError, TypeError))
71
72 def test___closure__(self):
73 a = 12
74 def f(): print(a)
75 c = f.__closure__
Ezio Melottie9615932010-01-24 19:26:24 +000076 self.assertIsInstance(c, tuple)
Georg Brandl4cb97d02009-09-04 11:20:54 +000077 self.assertEqual(len(c), 1)
78 # don't have a type object handy
79 self.assertEqual(c[0].__class__.__name__, "cell")
80 self.cannot_set_attr(f, "__closure__", c, AttributeError)
81
82 def test_empty_cell(self):
83 def f(): print(a)
84 try:
85 f.__closure__[0].cell_contents
86 except ValueError:
87 pass
88 else:
89 self.fail("shouldn't be able to read an empty cell")
90 a = 12
Barry Warsaw4a420a02001-01-15 20:30:15 +000091
Georg Brandl60d14562008-02-05 18:31:41 +000092 def test___name__(self):
93 self.assertEqual(self.b.__name__, 'b')
94 self.b.__name__ = 'c'
95 self.assertEqual(self.b.__name__, 'c')
96 self.b.__name__ = 'd'
97 self.assertEqual(self.b.__name__, 'd')
98 # __name__ and __name__ must be a string
99 self.cannot_set_attr(self.b, '__name__', 7, TypeError)
100 # __name__ must be available when in restricted mode. Exec will raise
101 # AttributeError if __name__ is not available on f.
102 s = """def f(): pass\nf.__name__"""
103 exec(s, {'__builtins__': {}})
104 # Test on methods, too
105 self.assertEqual(self.fi.a.__name__, 'a')
106 self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000107
Antoine Pitrou86a36b52011-11-25 18:56:07 +0100108 def test___qualname__(self):
109 # PEP 3155
110 self.assertEqual(self.b.__qualname__, 'FuncAttrsTest.setUp.<locals>.b')
111 self.assertEqual(FuncAttrsTest.setUp.__qualname__, 'FuncAttrsTest.setUp')
112 self.assertEqual(global_function.__qualname__, 'global_function')
113 self.assertEqual(global_function().__qualname__,
114 'global_function.<locals>.<lambda>')
115 self.assertEqual(global_function()().__qualname__,
116 'global_function.<locals>.inner_function')
117 self.assertEqual(global_function()()().__qualname__,
118 'global_function.<locals>.inner_function.<locals>.LocalClass')
119 self.b.__qualname__ = 'c'
120 self.assertEqual(self.b.__qualname__, 'c')
121 self.b.__qualname__ = 'd'
122 self.assertEqual(self.b.__qualname__, 'd')
123 # __qualname__ must be a string
124 self.cannot_set_attr(self.b, '__qualname__', 7, TypeError)
125
Georg Brandl60d14562008-02-05 18:31:41 +0000126 def test___code__(self):
127 num_one, num_two = 7, 8
128 def a(): pass
129 def b(): return 12
130 def c(): return num_one
131 def d(): return num_two
132 def e(): return num_one, num_two
133 for func in [a, b, c, d, e]:
134 self.assertEqual(type(func.__code__), types.CodeType)
135 self.assertEqual(c(), 7)
136 self.assertEqual(d(), 8)
137 d.__code__ = c.__code__
138 self.assertEqual(c.__code__, d.__code__)
139 self.assertEqual(c(), 7)
140 # self.assertEqual(d(), 7)
Georg Brandl4cb97d02009-09-04 11:20:54 +0000141 try:
142 b.__code__ = c.__code__
143 except ValueError:
144 pass
145 else:
146 self.fail("__code__ with different numbers of free vars should "
147 "not be possible")
148 try:
149 e.__code__ = d.__code__
150 except ValueError:
151 pass
152 else:
153 self.fail("__code__ with different numbers of free vars should "
154 "not be possible")
Barry Warsawc1e100f2001-02-26 18:07:26 +0000155
Georg Brandl60d14562008-02-05 18:31:41 +0000156 def test_blank_func_defaults(self):
157 self.assertEqual(self.b.__defaults__, None)
158 del self.b.__defaults__
159 self.assertEqual(self.b.__defaults__, None)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000160
Georg Brandl60d14562008-02-05 18:31:41 +0000161 def test_func_default_args(self):
162 def first_func(a, b):
163 return a+b
164 def second_func(a=1, b=2):
165 return a+b
166 self.assertEqual(first_func.__defaults__, None)
167 self.assertEqual(second_func.__defaults__, (1, 2))
168 first_func.__defaults__ = (1, 2)
169 self.assertEqual(first_func.__defaults__, (1, 2))
170 self.assertEqual(first_func(), 3)
171 self.assertEqual(first_func(3), 5)
172 self.assertEqual(first_func(3, 5), 8)
173 del second_func.__defaults__
174 self.assertEqual(second_func.__defaults__, None)
Georg Brandl4cb97d02009-09-04 11:20:54 +0000175 try:
176 second_func()
177 except TypeError:
178 pass
179 else:
180 self.fail("__defaults__ does not update; deleting it does not "
181 "remove requirement")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000182
Georg Brandl4cb97d02009-09-04 11:20:54 +0000183
184class InstancemethodAttrTest(FuncAttrsTest):
Barry Warsaw4a420a02001-01-15 20:30:15 +0000185
Georg Brandl60d14562008-02-05 18:31:41 +0000186 def test___class__(self):
187 self.assertEqual(self.fi.a.__self__.__class__, self.F)
188 self.cannot_set_attr(self.fi.a, "__class__", self.F, TypeError)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000189
Georg Brandl60d14562008-02-05 18:31:41 +0000190 def test___func__(self):
191 self.assertEqual(self.fi.a.__func__, self.F.a)
192 self.cannot_set_attr(self.fi.a, "__func__", self.F.a, AttributeError)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000193
Georg Brandl60d14562008-02-05 18:31:41 +0000194 def test___self__(self):
195 self.assertEqual(self.fi.a.__self__, self.fi)
196 self.cannot_set_attr(self.fi.a, "__self__", self.fi, AttributeError)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000197
Georg Brandl60d14562008-02-05 18:31:41 +0000198 def test___func___non_method(self):
199 # Behavior should be the same when a method is added via an attr
200 # assignment
201 self.fi.id = types.MethodType(id, self.fi)
202 self.assertEqual(self.fi.id(), id(self.fi))
203 # Test usage
Georg Brandl4cb97d02009-09-04 11:20:54 +0000204 try:
205 self.fi.id.unknown_attr
206 except AttributeError:
207 pass
208 else:
209 self.fail("using unknown attributes should raise AttributeError")
Georg Brandl60d14562008-02-05 18:31:41 +0000210 # Test assignment and deletion
211 self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000212
Georg Brandl4cb97d02009-09-04 11:20:54 +0000213
Georg Brandl60d14562008-02-05 18:31:41 +0000214class ArbitraryFunctionAttrTest(FuncAttrsTest):
215 def test_set_attr(self):
216 self.b.known_attr = 7
217 self.assertEqual(self.b.known_attr, 7)
Georg Brandl4cb97d02009-09-04 11:20:54 +0000218 try:
219 self.fi.a.known_attr = 7
220 except AttributeError:
221 pass
222 else:
223 self.fail("setting attributes on methods should raise error")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000224
Georg Brandl60d14562008-02-05 18:31:41 +0000225 def test_delete_unknown_attr(self):
Georg Brandl4cb97d02009-09-04 11:20:54 +0000226 try:
227 del self.b.unknown_attr
228 except AttributeError:
229 pass
230 else:
231 self.fail("deleting unknown attribute should raise TypeError")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000232
Georg Brandl60d14562008-02-05 18:31:41 +0000233 def test_unset_attr(self):
234 for func in [self.b, self.fi.a]:
Georg Brandl4cb97d02009-09-04 11:20:54 +0000235 try:
236 func.non_existent_attr
237 except AttributeError:
238 pass
239 else:
240 self.fail("using unknown attributes should raise "
241 "AttributeError")
242
Barry Warsaw4a420a02001-01-15 20:30:15 +0000243
Georg Brandl60d14562008-02-05 18:31:41 +0000244class FunctionDictsTest(FuncAttrsTest):
245 def test_setting_dict_to_invalid(self):
246 self.cannot_set_attr(self.b, '__dict__', None, TypeError)
Raymond Hettingerf80680d2008-02-06 00:07:11 +0000247 from collections import UserDict
Georg Brandl60d14562008-02-05 18:31:41 +0000248 d = UserDict({'known_attr': 7})
249 self.cannot_set_attr(self.fi.a.__func__, '__dict__', d, TypeError)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000250
Georg Brandl60d14562008-02-05 18:31:41 +0000251 def test_setting_dict_to_valid(self):
252 d = {'known_attr': 7}
253 self.b.__dict__ = d
254 # Test assignment
Georg Brandl4cb97d02009-09-04 11:20:54 +0000255 self.assertIs(d, self.b.__dict__)
Georg Brandl60d14562008-02-05 18:31:41 +0000256 # ... and on all the different ways of referencing the method's func
257 self.F.a.__dict__ = d
Georg Brandl4cb97d02009-09-04 11:20:54 +0000258 self.assertIs(d, self.fi.a.__func__.__dict__)
259 self.assertIs(d, self.fi.a.__dict__)
Georg Brandl60d14562008-02-05 18:31:41 +0000260 # Test value
261 self.assertEqual(self.b.known_attr, 7)
262 self.assertEqual(self.b.__dict__['known_attr'], 7)
263 # ... and again, on all the different method's names
264 self.assertEqual(self.fi.a.__func__.known_attr, 7)
265 self.assertEqual(self.fi.a.known_attr, 7)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000266
Georg Brandl60d14562008-02-05 18:31:41 +0000267 def test_delete___dict__(self):
Georg Brandl4cb97d02009-09-04 11:20:54 +0000268 try:
269 del self.b.__dict__
270 except TypeError:
271 pass
272 else:
273 self.fail("deleting function dictionary should raise TypeError")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000274
Georg Brandl60d14562008-02-05 18:31:41 +0000275 def test_unassigned_dict(self):
276 self.assertEqual(self.b.__dict__, {})
Barry Warsaw4a420a02001-01-15 20:30:15 +0000277
Georg Brandl60d14562008-02-05 18:31:41 +0000278 def test_func_as_dict_key(self):
279 value = "Some string"
280 d = {}
281 d[self.b] = value
282 self.assertEqual(d[self.b], value)
Barry Warsaw534c60f2001-01-15 21:00:02 +0000283
Georg Brandl4cb97d02009-09-04 11:20:54 +0000284
Georg Brandl60d14562008-02-05 18:31:41 +0000285class FunctionDocstringTest(FuncAttrsTest):
286 def test_set_docstring_attr(self):
287 self.assertEqual(self.b.__doc__, None)
288 docstr = "A test method that does nothing"
289 self.b.__doc__ = docstr
290 self.F.a.__doc__ = docstr
291 self.assertEqual(self.b.__doc__, docstr)
292 self.assertEqual(self.fi.a.__doc__, docstr)
293 self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError)
Guido van Rossumbd131492001-09-18 03:28:54 +0000294
Georg Brandl60d14562008-02-05 18:31:41 +0000295 def test_delete_docstring(self):
296 self.b.__doc__ = "The docstring"
297 del self.b.__doc__
298 self.assertEqual(self.b.__doc__, None)
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000299
Georg Brandl4cb97d02009-09-04 11:20:54 +0000300
Mark Dickinson211c6252009-02-01 10:28:51 +0000301def cell(value):
302 """Create a cell containing the given value."""
303 def f():
304 print(a)
305 a = value
306 return f.__closure__[0]
307
308def empty_cell(empty=True):
309 """Create an empty cell."""
310 def f():
311 print(a)
312 # the intent of the following line is simply "if False:"; it's
313 # spelt this way to avoid the danger that a future optimization
314 # might simply remove an "if False:" code block.
315 if not empty:
316 a = 1729
317 return f.__closure__[0]
318
Georg Brandl4cb97d02009-09-04 11:20:54 +0000319
Mark Dickinson211c6252009-02-01 10:28:51 +0000320class CellTest(unittest.TestCase):
321 def test_comparison(self):
322 # These tests are here simply to exercise the comparison code;
323 # their presence should not be interpreted as providing any
324 # guarantees about the semantics (or even existence) of cell
325 # comparisons in future versions of CPython.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000326 self.assertTrue(cell(2) < cell(3))
327 self.assertTrue(empty_cell() < cell('saturday'))
328 self.assertTrue(empty_cell() == empty_cell())
329 self.assertTrue(cell(-36) == cell(-36.0))
330 self.assertTrue(cell(True) > empty_cell())
Mark Dickinson211c6252009-02-01 10:28:51 +0000331
Georg Brandl4cb97d02009-09-04 11:20:54 +0000332
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000333class StaticMethodAttrsTest(unittest.TestCase):
334 def test_func_attribute(self):
335 def f():
336 pass
337
338 c = classmethod(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000339 self.assertTrue(c.__func__ is f)
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000340
341 s = staticmethod(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000342 self.assertTrue(s.__func__ is f)
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000343
Mark Dickinson211c6252009-02-01 10:28:51 +0000344
Antoine Pitrou5b629422011-12-23 12:40:16 +0100345class BuiltinFunctionPropertiesTest(unittest.TestCase):
346 # XXX Not sure where this should really go since I can't find a
347 # test module specifically for builtin_function_or_method.
348
349 def test_builtin__qualname__(self):
350 import time
351
352 # builtin function:
353 self.assertEqual(len.__qualname__, 'len')
354 self.assertEqual(time.time.__qualname__, 'time')
355
356 # builtin classmethod:
357 self.assertEqual(dict.fromkeys.__qualname__, 'dict.fromkeys')
358 self.assertEqual(float.__getformat__.__qualname__,
359 'float.__getformat__')
360
361 # builtin staticmethod:
362 self.assertEqual(str.maketrans.__qualname__, 'str.maketrans')
363 self.assertEqual(bytes.maketrans.__qualname__, 'bytes.maketrans')
364
365 # builtin bound instance method:
366 self.assertEqual([1, 2, 3].append.__qualname__, 'list.append')
367 self.assertEqual({'foo': 'bar'}.pop.__qualname__, 'dict.pop')
368
369
Georg Brandl60d14562008-02-05 18:31:41 +0000370def test_main():
Georg Brandl4cb97d02009-09-04 11:20:54 +0000371 support.run_unittest(FunctionPropertiesTest, InstancemethodAttrTest,
Georg Brandl60d14562008-02-05 18:31:41 +0000372 ArbitraryFunctionAttrTest, FunctionDictsTest,
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000373 FunctionDocstringTest, CellTest,
Antoine Pitrou5b629422011-12-23 12:40:16 +0100374 StaticMethodAttrsTest,
375 BuiltinFunctionPropertiesTest)
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000376
Georg Brandl60d14562008-02-05 18:31:41 +0000377if __name__ == "__main__":
378 test_main()