blob: 4d1936879ec3f664aeb12f5be705e27932fa518d [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
Georg Brandl60d14562008-02-05 18:31:41 +00005class FuncAttrsTest(unittest.TestCase):
6 def setUp(self):
7 class F:
8 def a(self):
9 pass
10 def b():
11 return 3
12 self.fi = F()
13 self.F = F
14 self.b = b
Barry Warsaw4a420a02001-01-15 20:30:15 +000015
Georg Brandl60d14562008-02-05 18:31:41 +000016 def cannot_set_attr(self, obj, name, value, exceptions):
17 try:
18 setattr(obj, name, value)
19 except exceptions:
20 pass
21 else:
22 self.fail("shouldn't be able to set %s to %r" % (name, value))
23 try:
24 delattr(obj, name)
25 except exceptions:
26 pass
27 else:
28 self.fail("shouldn't be able to del %s" % name)
Barry Warsaw4a420a02001-01-15 20:30:15 +000029
Jeremy Hylton4f0dcc92003-01-31 18:33:18 +000030
Georg Brandl60d14562008-02-05 18:31:41 +000031class FunctionPropertiesTest(FuncAttrsTest):
32 # Include the external setUp method that is common to all tests
33 def test_module(self):
34 self.assertEqual(self.b.__module__, __name__)
Barry Warsaw4a420a02001-01-15 20:30:15 +000035
Georg Brandl60d14562008-02-05 18:31:41 +000036 def test_dir_includes_correct_attrs(self):
37 self.b.known_attr = 7
Benjamin Peterson577473f2010-01-19 00:09:57 +000038 self.assertIn('known_attr', dir(self.b),
Georg Brandl60d14562008-02-05 18:31:41 +000039 "set attributes not in dir listing of method")
40 # Test on underlying function object of method
41 self.F.a.known_attr = 7
Benjamin Peterson577473f2010-01-19 00:09:57 +000042 self.assertIn('known_attr', dir(self.fi.a), "set attribute on function "
Georg Brandl60d14562008-02-05 18:31:41 +000043 "implementations, should show up in next dir")
Barry Warsawc1e100f2001-02-26 18:07:26 +000044
Georg Brandl60d14562008-02-05 18:31:41 +000045 def test_duplicate_function_equality(self):
46 # Body of `duplicate' is the exact same as self.b
47 def duplicate():
48 'my docstring'
49 return 3
50 self.assertNotEqual(self.b, duplicate)
Barry Warsaw4a420a02001-01-15 20:30:15 +000051
Georg Brandl60d14562008-02-05 18:31:41 +000052 def test_copying___code__(self):
53 def test(): pass
54 self.assertEqual(test(), None)
55 test.__code__ = self.b.__code__
56 self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily
Barry Warsaw4a420a02001-01-15 20:30:15 +000057
Georg Brandl60d14562008-02-05 18:31:41 +000058 def test___globals__(self):
Georg Brandl4cb97d02009-09-04 11:20:54 +000059 self.assertIs(self.b.__globals__, globals())
60 self.cannot_set_attr(self.b, '__globals__', 2,
61 (AttributeError, TypeError))
62
63 def test___closure__(self):
64 a = 12
65 def f(): print(a)
66 c = f.__closure__
Ezio Melottie9615932010-01-24 19:26:24 +000067 self.assertIsInstance(c, tuple)
Georg Brandl4cb97d02009-09-04 11:20:54 +000068 self.assertEqual(len(c), 1)
69 # don't have a type object handy
70 self.assertEqual(c[0].__class__.__name__, "cell")
71 self.cannot_set_attr(f, "__closure__", c, AttributeError)
72
73 def test_empty_cell(self):
74 def f(): print(a)
75 try:
76 f.__closure__[0].cell_contents
77 except ValueError:
78 pass
79 else:
80 self.fail("shouldn't be able to read an empty cell")
81 a = 12
Barry Warsaw4a420a02001-01-15 20:30:15 +000082
Georg Brandl60d14562008-02-05 18:31:41 +000083 def test___name__(self):
84 self.assertEqual(self.b.__name__, 'b')
85 self.b.__name__ = 'c'
86 self.assertEqual(self.b.__name__, 'c')
87 self.b.__name__ = 'd'
88 self.assertEqual(self.b.__name__, 'd')
89 # __name__ and __name__ must be a string
90 self.cannot_set_attr(self.b, '__name__', 7, TypeError)
91 # __name__ must be available when in restricted mode. Exec will raise
92 # AttributeError if __name__ is not available on f.
93 s = """def f(): pass\nf.__name__"""
94 exec(s, {'__builtins__': {}})
95 # Test on methods, too
96 self.assertEqual(self.fi.a.__name__, 'a')
97 self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError)
Barry Warsawc1e100f2001-02-26 18:07:26 +000098
Georg Brandl60d14562008-02-05 18:31:41 +000099 def test___code__(self):
100 num_one, num_two = 7, 8
101 def a(): pass
102 def b(): return 12
103 def c(): return num_one
104 def d(): return num_two
105 def e(): return num_one, num_two
106 for func in [a, b, c, d, e]:
107 self.assertEqual(type(func.__code__), types.CodeType)
108 self.assertEqual(c(), 7)
109 self.assertEqual(d(), 8)
110 d.__code__ = c.__code__
111 self.assertEqual(c.__code__, d.__code__)
112 self.assertEqual(c(), 7)
113 # self.assertEqual(d(), 7)
Georg Brandl4cb97d02009-09-04 11:20:54 +0000114 try:
115 b.__code__ = c.__code__
116 except ValueError:
117 pass
118 else:
119 self.fail("__code__ with different numbers of free vars should "
120 "not be possible")
121 try:
122 e.__code__ = d.__code__
123 except ValueError:
124 pass
125 else:
126 self.fail("__code__ with different numbers of free vars should "
127 "not be possible")
Barry Warsawc1e100f2001-02-26 18:07:26 +0000128
Georg Brandl60d14562008-02-05 18:31:41 +0000129 def test_blank_func_defaults(self):
130 self.assertEqual(self.b.__defaults__, None)
131 del self.b.__defaults__
132 self.assertEqual(self.b.__defaults__, None)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000133
Georg Brandl60d14562008-02-05 18:31:41 +0000134 def test_func_default_args(self):
135 def first_func(a, b):
136 return a+b
137 def second_func(a=1, b=2):
138 return a+b
139 self.assertEqual(first_func.__defaults__, None)
140 self.assertEqual(second_func.__defaults__, (1, 2))
141 first_func.__defaults__ = (1, 2)
142 self.assertEqual(first_func.__defaults__, (1, 2))
143 self.assertEqual(first_func(), 3)
144 self.assertEqual(first_func(3), 5)
145 self.assertEqual(first_func(3, 5), 8)
146 del second_func.__defaults__
147 self.assertEqual(second_func.__defaults__, None)
Georg Brandl4cb97d02009-09-04 11:20:54 +0000148 try:
149 second_func()
150 except TypeError:
151 pass
152 else:
153 self.fail("__defaults__ does not update; deleting it does not "
154 "remove requirement")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000155
Georg Brandl4cb97d02009-09-04 11:20:54 +0000156
157class InstancemethodAttrTest(FuncAttrsTest):
Barry Warsaw4a420a02001-01-15 20:30:15 +0000158
Georg Brandl60d14562008-02-05 18:31:41 +0000159 def test___class__(self):
160 self.assertEqual(self.fi.a.__self__.__class__, self.F)
161 self.cannot_set_attr(self.fi.a, "__class__", self.F, TypeError)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000162
Georg Brandl60d14562008-02-05 18:31:41 +0000163 def test___func__(self):
164 self.assertEqual(self.fi.a.__func__, self.F.a)
165 self.cannot_set_attr(self.fi.a, "__func__", self.F.a, AttributeError)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000166
Georg Brandl60d14562008-02-05 18:31:41 +0000167 def test___self__(self):
168 self.assertEqual(self.fi.a.__self__, self.fi)
169 self.cannot_set_attr(self.fi.a, "__self__", self.fi, AttributeError)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000170
Georg Brandl60d14562008-02-05 18:31:41 +0000171 def test___func___non_method(self):
172 # Behavior should be the same when a method is added via an attr
173 # assignment
174 self.fi.id = types.MethodType(id, self.fi)
175 self.assertEqual(self.fi.id(), id(self.fi))
176 # Test usage
Georg Brandl4cb97d02009-09-04 11:20:54 +0000177 try:
178 self.fi.id.unknown_attr
179 except AttributeError:
180 pass
181 else:
182 self.fail("using unknown attributes should raise AttributeError")
Georg Brandl60d14562008-02-05 18:31:41 +0000183 # Test assignment and deletion
184 self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000185
Georg Brandl4cb97d02009-09-04 11:20:54 +0000186
Georg Brandl60d14562008-02-05 18:31:41 +0000187class ArbitraryFunctionAttrTest(FuncAttrsTest):
188 def test_set_attr(self):
189 self.b.known_attr = 7
190 self.assertEqual(self.b.known_attr, 7)
Georg Brandl4cb97d02009-09-04 11:20:54 +0000191 try:
192 self.fi.a.known_attr = 7
193 except AttributeError:
194 pass
195 else:
196 self.fail("setting attributes on methods should raise error")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000197
Georg Brandl60d14562008-02-05 18:31:41 +0000198 def test_delete_unknown_attr(self):
Georg Brandl4cb97d02009-09-04 11:20:54 +0000199 try:
200 del self.b.unknown_attr
201 except AttributeError:
202 pass
203 else:
204 self.fail("deleting unknown attribute should raise TypeError")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000205
Georg Brandl60d14562008-02-05 18:31:41 +0000206 def test_unset_attr(self):
207 for func in [self.b, self.fi.a]:
Georg Brandl4cb97d02009-09-04 11:20:54 +0000208 try:
209 func.non_existent_attr
210 except AttributeError:
211 pass
212 else:
213 self.fail("using unknown attributes should raise "
214 "AttributeError")
215
Barry Warsaw4a420a02001-01-15 20:30:15 +0000216
Georg Brandl60d14562008-02-05 18:31:41 +0000217class FunctionDictsTest(FuncAttrsTest):
218 def test_setting_dict_to_invalid(self):
219 self.cannot_set_attr(self.b, '__dict__', None, TypeError)
Raymond Hettingerf80680d2008-02-06 00:07:11 +0000220 from collections import UserDict
Georg Brandl60d14562008-02-05 18:31:41 +0000221 d = UserDict({'known_attr': 7})
222 self.cannot_set_attr(self.fi.a.__func__, '__dict__', d, TypeError)
Barry Warsawc1e100f2001-02-26 18:07:26 +0000223
Georg Brandl60d14562008-02-05 18:31:41 +0000224 def test_setting_dict_to_valid(self):
225 d = {'known_attr': 7}
226 self.b.__dict__ = d
227 # Test assignment
Georg Brandl4cb97d02009-09-04 11:20:54 +0000228 self.assertIs(d, self.b.__dict__)
Georg Brandl60d14562008-02-05 18:31:41 +0000229 # ... and on all the different ways of referencing the method's func
230 self.F.a.__dict__ = d
Georg Brandl4cb97d02009-09-04 11:20:54 +0000231 self.assertIs(d, self.fi.a.__func__.__dict__)
232 self.assertIs(d, self.fi.a.__dict__)
Georg Brandl60d14562008-02-05 18:31:41 +0000233 # Test value
234 self.assertEqual(self.b.known_attr, 7)
235 self.assertEqual(self.b.__dict__['known_attr'], 7)
236 # ... and again, on all the different method's names
237 self.assertEqual(self.fi.a.__func__.known_attr, 7)
238 self.assertEqual(self.fi.a.known_attr, 7)
Barry Warsaw4a420a02001-01-15 20:30:15 +0000239
Georg Brandl60d14562008-02-05 18:31:41 +0000240 def test_delete___dict__(self):
Georg Brandl4cb97d02009-09-04 11:20:54 +0000241 try:
242 del self.b.__dict__
243 except TypeError:
244 pass
245 else:
246 self.fail("deleting function dictionary should raise TypeError")
Barry Warsaw4a420a02001-01-15 20:30:15 +0000247
Georg Brandl60d14562008-02-05 18:31:41 +0000248 def test_unassigned_dict(self):
249 self.assertEqual(self.b.__dict__, {})
Barry Warsaw4a420a02001-01-15 20:30:15 +0000250
Georg Brandl60d14562008-02-05 18:31:41 +0000251 def test_func_as_dict_key(self):
252 value = "Some string"
253 d = {}
254 d[self.b] = value
255 self.assertEqual(d[self.b], value)
Barry Warsaw534c60f2001-01-15 21:00:02 +0000256
Georg Brandl4cb97d02009-09-04 11:20:54 +0000257
Georg Brandl60d14562008-02-05 18:31:41 +0000258class FunctionDocstringTest(FuncAttrsTest):
259 def test_set_docstring_attr(self):
260 self.assertEqual(self.b.__doc__, None)
261 docstr = "A test method that does nothing"
262 self.b.__doc__ = docstr
263 self.F.a.__doc__ = docstr
264 self.assertEqual(self.b.__doc__, docstr)
265 self.assertEqual(self.fi.a.__doc__, docstr)
266 self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError)
Guido van Rossumbd131492001-09-18 03:28:54 +0000267
Georg Brandl60d14562008-02-05 18:31:41 +0000268 def test_delete_docstring(self):
269 self.b.__doc__ = "The docstring"
270 del self.b.__doc__
271 self.assertEqual(self.b.__doc__, None)
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000272
Georg Brandl4cb97d02009-09-04 11:20:54 +0000273
Mark Dickinson211c6252009-02-01 10:28:51 +0000274def cell(value):
275 """Create a cell containing the given value."""
276 def f():
277 print(a)
278 a = value
279 return f.__closure__[0]
280
281def empty_cell(empty=True):
282 """Create an empty cell."""
283 def f():
284 print(a)
285 # the intent of the following line is simply "if False:"; it's
286 # spelt this way to avoid the danger that a future optimization
287 # might simply remove an "if False:" code block.
288 if not empty:
289 a = 1729
290 return f.__closure__[0]
291
Georg Brandl4cb97d02009-09-04 11:20:54 +0000292
Mark Dickinson211c6252009-02-01 10:28:51 +0000293class CellTest(unittest.TestCase):
294 def test_comparison(self):
295 # These tests are here simply to exercise the comparison code;
296 # their presence should not be interpreted as providing any
297 # guarantees about the semantics (or even existence) of cell
298 # comparisons in future versions of CPython.
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000299 self.assertTrue(cell(2) < cell(3))
300 self.assertTrue(empty_cell() < cell('saturday'))
301 self.assertTrue(empty_cell() == empty_cell())
302 self.assertTrue(cell(-36) == cell(-36.0))
303 self.assertTrue(cell(True) > empty_cell())
Mark Dickinson211c6252009-02-01 10:28:51 +0000304
Georg Brandl4cb97d02009-09-04 11:20:54 +0000305
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000306class StaticMethodAttrsTest(unittest.TestCase):
307 def test_func_attribute(self):
308 def f():
309 pass
310
311 c = classmethod(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000312 self.assertTrue(c.__func__ is f)
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000313
314 s = staticmethod(f)
Benjamin Petersonc9c0f202009-06-30 23:06:06 +0000315 self.assertTrue(s.__func__ is f)
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000316
Mark Dickinson211c6252009-02-01 10:28:51 +0000317
Georg Brandl60d14562008-02-05 18:31:41 +0000318def test_main():
Georg Brandl4cb97d02009-09-04 11:20:54 +0000319 support.run_unittest(FunctionPropertiesTest, InstancemethodAttrTest,
Georg Brandl60d14562008-02-05 18:31:41 +0000320 ArbitraryFunctionAttrTest, FunctionDictsTest,
Raymond Hettinger2bcde142009-05-29 04:52:27 +0000321 FunctionDocstringTest, CellTest,
322 StaticMethodAttrsTest)
Guido van Rossumd9d1d4a2001-09-17 23:46:56 +0000323
Georg Brandl60d14562008-02-05 18:31:41 +0000324if __name__ == "__main__":
325 test_main()