PageRenderTime 44ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/Lib/test/test_funcattrs.py

https://gitlab.com/unofficial-mirrors/cpython
Python | 377 lines | 356 code | 14 blank | 7 comment | 11 complexity | 31431ef139a7fe93eb4a8503d36a7b42 MD5 | raw file
  1. import types
  2. import unittest
  3. def global_function():
  4. def inner_function():
  5. class LocalClass:
  6. pass
  7. global inner_global_function
  8. def inner_global_function():
  9. def inner_function2():
  10. pass
  11. return inner_function2
  12. return LocalClass
  13. return lambda: inner_function
  14. class 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
  24. def cannot_set_attr(self, obj, name, value, exceptions):
  25. try:
  26. setattr(obj, name, value)
  27. except exceptions:
  28. pass
  29. else:
  30. self.fail("shouldn't be able to set %s to %r" % (name, value))
  31. try:
  32. delattr(obj, name)
  33. except exceptions:
  34. pass
  35. else:
  36. self.fail("shouldn't be able to del %s" % name)
  37. class FunctionPropertiesTest(FuncAttrsTest):
  38. # Include the external setUp method that is common to all tests
  39. def test_module(self):
  40. self.assertEqual(self.b.__module__, __name__)
  41. def test_dir_includes_correct_attrs(self):
  42. self.b.known_attr = 7
  43. self.assertIn('known_attr', dir(self.b),
  44. "set attributes not in dir listing of method")
  45. # Test on underlying function object of method
  46. self.F.a.known_attr = 7
  47. self.assertIn('known_attr', dir(self.fi.a), "set attribute on function "
  48. "implementations, should show up in next dir")
  49. def test_duplicate_function_equality(self):
  50. # Body of `duplicate' is the exact same as self.b
  51. def duplicate():
  52. 'my docstring'
  53. return 3
  54. self.assertNotEqual(self.b, duplicate)
  55. def test_copying___code__(self):
  56. def test(): pass
  57. self.assertEqual(test(), None)
  58. test.__code__ = self.b.__code__
  59. self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily
  60. def test___globals__(self):
  61. self.assertIs(self.b.__globals__, globals())
  62. self.cannot_set_attr(self.b, '__globals__', 2,
  63. (AttributeError, TypeError))
  64. def test___closure__(self):
  65. a = 12
  66. def f(): print(a)
  67. c = f.__closure__
  68. self.assertIsInstance(c, tuple)
  69. self.assertEqual(len(c), 1)
  70. # don't have a type object handy
  71. self.assertEqual(c[0].__class__.__name__, "cell")
  72. self.cannot_set_attr(f, "__closure__", c, AttributeError)
  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
  82. def test___name__(self):
  83. self.assertEqual(self.b.__name__, 'b')
  84. self.b.__name__ = 'c'
  85. self.assertEqual(self.b.__name__, 'c')
  86. self.b.__name__ = 'd'
  87. self.assertEqual(self.b.__name__, 'd')
  88. # __name__ and __name__ must be a string
  89. self.cannot_set_attr(self.b, '__name__', 7, TypeError)
  90. # __name__ must be available when in restricted mode. Exec will raise
  91. # AttributeError if __name__ is not available on f.
  92. s = """def f(): pass\nf.__name__"""
  93. exec(s, {'__builtins__': {}})
  94. # Test on methods, too
  95. self.assertEqual(self.fi.a.__name__, 'a')
  96. self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError)
  97. def test___qualname__(self):
  98. # PEP 3155
  99. self.assertEqual(self.b.__qualname__, 'FuncAttrsTest.setUp.<locals>.b')
  100. self.assertEqual(FuncAttrsTest.setUp.__qualname__, 'FuncAttrsTest.setUp')
  101. self.assertEqual(global_function.__qualname__, 'global_function')
  102. self.assertEqual(global_function().__qualname__,
  103. 'global_function.<locals>.<lambda>')
  104. self.assertEqual(global_function()().__qualname__,
  105. 'global_function.<locals>.inner_function')
  106. self.assertEqual(global_function()()().__qualname__,
  107. 'global_function.<locals>.inner_function.<locals>.LocalClass')
  108. self.assertEqual(inner_global_function.__qualname__, 'inner_global_function')
  109. self.assertEqual(inner_global_function().__qualname__, 'inner_global_function.<locals>.inner_function2')
  110. self.b.__qualname__ = 'c'
  111. self.assertEqual(self.b.__qualname__, 'c')
  112. self.b.__qualname__ = 'd'
  113. self.assertEqual(self.b.__qualname__, 'd')
  114. # __qualname__ must be a string
  115. self.cannot_set_attr(self.b, '__qualname__', 7, TypeError)
  116. def test___code__(self):
  117. num_one, num_two = 7, 8
  118. def a(): pass
  119. def b(): return 12
  120. def c(): return num_one
  121. def d(): return num_two
  122. def e(): return num_one, num_two
  123. for func in [a, b, c, d, e]:
  124. self.assertEqual(type(func.__code__), types.CodeType)
  125. self.assertEqual(c(), 7)
  126. self.assertEqual(d(), 8)
  127. d.__code__ = c.__code__
  128. self.assertEqual(c.__code__, d.__code__)
  129. self.assertEqual(c(), 7)
  130. # self.assertEqual(d(), 7)
  131. try:
  132. b.__code__ = c.__code__
  133. except ValueError:
  134. pass
  135. else:
  136. self.fail("__code__ with different numbers of free vars should "
  137. "not be possible")
  138. try:
  139. e.__code__ = d.__code__
  140. except ValueError:
  141. pass
  142. else:
  143. self.fail("__code__ with different numbers of free vars should "
  144. "not be possible")
  145. def test_blank_func_defaults(self):
  146. self.assertEqual(self.b.__defaults__, None)
  147. del self.b.__defaults__
  148. self.assertEqual(self.b.__defaults__, None)
  149. def test_func_default_args(self):
  150. def first_func(a, b):
  151. return a+b
  152. def second_func(a=1, b=2):
  153. return a+b
  154. self.assertEqual(first_func.__defaults__, None)
  155. self.assertEqual(second_func.__defaults__, (1, 2))
  156. first_func.__defaults__ = (1, 2)
  157. self.assertEqual(first_func.__defaults__, (1, 2))
  158. self.assertEqual(first_func(), 3)
  159. self.assertEqual(first_func(3), 5)
  160. self.assertEqual(first_func(3, 5), 8)
  161. del second_func.__defaults__
  162. self.assertEqual(second_func.__defaults__, None)
  163. try:
  164. second_func()
  165. except TypeError:
  166. pass
  167. else:
  168. self.fail("__defaults__ does not update; deleting it does not "
  169. "remove requirement")
  170. class InstancemethodAttrTest(FuncAttrsTest):
  171. def test___class__(self):
  172. self.assertEqual(self.fi.a.__self__.__class__, self.F)
  173. self.cannot_set_attr(self.fi.a, "__class__", self.F, TypeError)
  174. def test___func__(self):
  175. self.assertEqual(self.fi.a.__func__, self.F.a)
  176. self.cannot_set_attr(self.fi.a, "__func__", self.F.a, AttributeError)
  177. def test___self__(self):
  178. self.assertEqual(self.fi.a.__self__, self.fi)
  179. self.cannot_set_attr(self.fi.a, "__self__", self.fi, AttributeError)
  180. def test___func___non_method(self):
  181. # Behavior should be the same when a method is added via an attr
  182. # assignment
  183. self.fi.id = types.MethodType(id, self.fi)
  184. self.assertEqual(self.fi.id(), id(self.fi))
  185. # Test usage
  186. try:
  187. self.fi.id.unknown_attr
  188. except AttributeError:
  189. pass
  190. else:
  191. self.fail("using unknown attributes should raise AttributeError")
  192. # Test assignment and deletion
  193. self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError)
  194. class ArbitraryFunctionAttrTest(FuncAttrsTest):
  195. def test_set_attr(self):
  196. self.b.known_attr = 7
  197. self.assertEqual(self.b.known_attr, 7)
  198. try:
  199. self.fi.a.known_attr = 7
  200. except AttributeError:
  201. pass
  202. else:
  203. self.fail("setting attributes on methods should raise error")
  204. def test_delete_unknown_attr(self):
  205. try:
  206. del self.b.unknown_attr
  207. except AttributeError:
  208. pass
  209. else:
  210. self.fail("deleting unknown attribute should raise TypeError")
  211. def test_unset_attr(self):
  212. for func in [self.b, self.fi.a]:
  213. try:
  214. func.non_existent_attr
  215. except AttributeError:
  216. pass
  217. else:
  218. self.fail("using unknown attributes should raise "
  219. "AttributeError")
  220. class FunctionDictsTest(FuncAttrsTest):
  221. def test_setting_dict_to_invalid(self):
  222. self.cannot_set_attr(self.b, '__dict__', None, TypeError)
  223. from collections import UserDict
  224. d = UserDict({'known_attr': 7})
  225. self.cannot_set_attr(self.fi.a.__func__, '__dict__', d, TypeError)
  226. def test_setting_dict_to_valid(self):
  227. d = {'known_attr': 7}
  228. self.b.__dict__ = d
  229. # Test assignment
  230. self.assertIs(d, self.b.__dict__)
  231. # ... and on all the different ways of referencing the method's func
  232. self.F.a.__dict__ = d
  233. self.assertIs(d, self.fi.a.__func__.__dict__)
  234. self.assertIs(d, self.fi.a.__dict__)
  235. # Test value
  236. self.assertEqual(self.b.known_attr, 7)
  237. self.assertEqual(self.b.__dict__['known_attr'], 7)
  238. # ... and again, on all the different method's names
  239. self.assertEqual(self.fi.a.__func__.known_attr, 7)
  240. self.assertEqual(self.fi.a.known_attr, 7)
  241. def test_delete___dict__(self):
  242. try:
  243. del self.b.__dict__
  244. except TypeError:
  245. pass
  246. else:
  247. self.fail("deleting function dictionary should raise TypeError")
  248. def test_unassigned_dict(self):
  249. self.assertEqual(self.b.__dict__, {})
  250. def test_func_as_dict_key(self):
  251. value = "Some string"
  252. d = {}
  253. d[self.b] = value
  254. self.assertEqual(d[self.b], value)
  255. class FunctionDocstringTest(FuncAttrsTest):
  256. def test_set_docstring_attr(self):
  257. self.assertEqual(self.b.__doc__, None)
  258. docstr = "A test method that does nothing"
  259. self.b.__doc__ = docstr
  260. self.F.a.__doc__ = docstr
  261. self.assertEqual(self.b.__doc__, docstr)
  262. self.assertEqual(self.fi.a.__doc__, docstr)
  263. self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError)
  264. def test_delete_docstring(self):
  265. self.b.__doc__ = "The docstring"
  266. del self.b.__doc__
  267. self.assertEqual(self.b.__doc__, None)
  268. def cell(value):
  269. """Create a cell containing the given value."""
  270. def f():
  271. print(a)
  272. a = value
  273. return f.__closure__[0]
  274. def empty_cell(empty=True):
  275. """Create an empty cell."""
  276. def f():
  277. print(a)
  278. # the intent of the following line is simply "if False:"; it's
  279. # spelt this way to avoid the danger that a future optimization
  280. # might simply remove an "if False:" code block.
  281. if not empty:
  282. a = 1729
  283. return f.__closure__[0]
  284. class CellTest(unittest.TestCase):
  285. def test_comparison(self):
  286. # These tests are here simply to exercise the comparison code;
  287. # their presence should not be interpreted as providing any
  288. # guarantees about the semantics (or even existence) of cell
  289. # comparisons in future versions of CPython.
  290. self.assertTrue(cell(2) < cell(3))
  291. self.assertTrue(empty_cell() < cell('saturday'))
  292. self.assertTrue(empty_cell() == empty_cell())
  293. self.assertTrue(cell(-36) == cell(-36.0))
  294. self.assertTrue(cell(True) > empty_cell())
  295. class StaticMethodAttrsTest(unittest.TestCase):
  296. def test_func_attribute(self):
  297. def f():
  298. pass
  299. c = classmethod(f)
  300. self.assertTrue(c.__func__ is f)
  301. s = staticmethod(f)
  302. self.assertTrue(s.__func__ is f)
  303. class BuiltinFunctionPropertiesTest(unittest.TestCase):
  304. # XXX Not sure where this should really go since I can't find a
  305. # test module specifically for builtin_function_or_method.
  306. def test_builtin__qualname__(self):
  307. import time
  308. # builtin function:
  309. self.assertEqual(len.__qualname__, 'len')
  310. self.assertEqual(time.time.__qualname__, 'time')
  311. # builtin classmethod:
  312. self.assertEqual(dict.fromkeys.__qualname__, 'dict.fromkeys')
  313. self.assertEqual(float.__getformat__.__qualname__,
  314. 'float.__getformat__')
  315. # builtin staticmethod:
  316. self.assertEqual(str.maketrans.__qualname__, 'str.maketrans')
  317. self.assertEqual(bytes.maketrans.__qualname__, 'bytes.maketrans')
  318. # builtin bound instance method:
  319. self.assertEqual([1, 2, 3].append.__qualname__, 'list.append')
  320. self.assertEqual({'foo': 'bar'}.pop.__qualname__, 'dict.pop')
  321. if __name__ == "__main__":
  322. unittest.main()