test_funcattrs.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353
  1. from test import test_support
  2. import types
  3. import unittest
  4. class FuncAttrsTest(unittest.TestCase):
  5. def setUp(self):
  6. class F:
  7. def a(self):
  8. pass
  9. def b():
  10. return 3
  11. self.f = F
  12. self.fi = F()
  13. self.b = b
  14. def cannot_set_attr(self, obj, name, value, exceptions):
  15. # Helper method for other tests.
  16. try:
  17. setattr(obj, name, value)
  18. except exceptions:
  19. pass
  20. else:
  21. self.fail("shouldn't be able to set %s to %r" % (name, value))
  22. try:
  23. delattr(obj, name)
  24. except exceptions:
  25. pass
  26. else:
  27. self.fail("shouldn't be able to del %s" % name)
  28. class FunctionPropertiesTest(FuncAttrsTest):
  29. # Include the external setUp method that is common to all tests
  30. def test_module(self):
  31. self.assertEqual(self.b.__module__, __name__)
  32. def test_dir_includes_correct_attrs(self):
  33. self.b.known_attr = 7
  34. self.assertIn('known_attr', dir(self.b),
  35. "set attributes not in dir listing of method")
  36. # Test on underlying function object of method
  37. self.f.a.im_func.known_attr = 7
  38. self.assertIn('known_attr', dir(self.f.a),
  39. "set attribute on unbound method implementation in "
  40. "class not in dir")
  41. self.assertIn('known_attr', dir(self.fi.a),
  42. "set attribute on unbound method implementations, "
  43. "should show up in next dir")
  44. def test_duplicate_function_equality(self):
  45. # Body of `duplicate' is the exact same as self.b
  46. def duplicate():
  47. 'my docstring'
  48. return 3
  49. self.assertNotEqual(self.b, duplicate)
  50. def test_copying_func_code(self):
  51. def test(): pass
  52. self.assertEqual(test(), None)
  53. test.func_code = self.b.func_code
  54. self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily
  55. def test_func_globals(self):
  56. self.assertIs(self.b.func_globals, globals())
  57. self.cannot_set_attr(self.b, 'func_globals', 2, TypeError)
  58. def test_func_closure(self):
  59. a = 12
  60. def f(): print a
  61. c = f.func_closure
  62. self.assertIsInstance(c, tuple)
  63. self.assertEqual(len(c), 1)
  64. # don't have a type object handy
  65. self.assertEqual(c[0].__class__.__name__, "cell")
  66. self.cannot_set_attr(f, "func_closure", c, TypeError)
  67. def test_empty_cell(self):
  68. def f(): print a
  69. try:
  70. f.func_closure[0].cell_contents
  71. except ValueError:
  72. pass
  73. else:
  74. self.fail("shouldn't be able to read an empty cell")
  75. a = 12
  76. def test_func_name(self):
  77. self.assertEqual(self.b.__name__, 'b')
  78. self.assertEqual(self.b.func_name, 'b')
  79. self.b.__name__ = 'c'
  80. self.assertEqual(self.b.__name__, 'c')
  81. self.assertEqual(self.b.func_name, 'c')
  82. self.b.func_name = 'd'
  83. self.assertEqual(self.b.__name__, 'd')
  84. self.assertEqual(self.b.func_name, 'd')
  85. # __name__ and func_name must be a string
  86. self.cannot_set_attr(self.b, '__name__', 7, TypeError)
  87. self.cannot_set_attr(self.b, 'func_name', 7, TypeError)
  88. # __name__ must be available when in restricted mode. Exec will raise
  89. # AttributeError if __name__ is not available on f.
  90. s = """def f(): pass\nf.__name__"""
  91. exec s in {'__builtins__': {}}
  92. # Test on methods, too
  93. self.assertEqual(self.f.a.__name__, 'a')
  94. self.assertEqual(self.fi.a.__name__, 'a')
  95. self.cannot_set_attr(self.f.a, "__name__", 'a', AttributeError)
  96. self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError)
  97. def test_func_code(self):
  98. num_one, num_two = 7, 8
  99. def a(): pass
  100. def b(): return 12
  101. def c(): return num_one
  102. def d(): return num_two
  103. def e(): return num_one, num_two
  104. for func in [a, b, c, d, e]:
  105. self.assertEqual(type(func.func_code), types.CodeType)
  106. self.assertEqual(c(), 7)
  107. self.assertEqual(d(), 8)
  108. d.func_code = c.func_code
  109. self.assertEqual(c.func_code, d.func_code)
  110. self.assertEqual(c(), 7)
  111. # self.assertEqual(d(), 7)
  112. try:
  113. b.func_code = c.func_code
  114. except ValueError:
  115. pass
  116. else:
  117. self.fail("func_code with different numbers of free vars should "
  118. "not be possible")
  119. try:
  120. e.func_code = d.func_code
  121. except ValueError:
  122. pass
  123. else:
  124. self.fail("func_code with different numbers of free vars should "
  125. "not be possible")
  126. def test_blank_func_defaults(self):
  127. self.assertEqual(self.b.func_defaults, None)
  128. del self.b.func_defaults
  129. self.assertEqual(self.b.func_defaults, None)
  130. def test_func_default_args(self):
  131. def first_func(a, b):
  132. return a+b
  133. def second_func(a=1, b=2):
  134. return a+b
  135. self.assertEqual(first_func.func_defaults, None)
  136. self.assertEqual(second_func.func_defaults, (1, 2))
  137. first_func.func_defaults = (1, 2)
  138. self.assertEqual(first_func.func_defaults, (1, 2))
  139. self.assertEqual(first_func(), 3)
  140. self.assertEqual(first_func(3), 5)
  141. self.assertEqual(first_func(3, 5), 8)
  142. del second_func.func_defaults
  143. self.assertEqual(second_func.func_defaults, None)
  144. try:
  145. second_func()
  146. except TypeError:
  147. pass
  148. else:
  149. self.fail("func_defaults does not update; deleting it does not "
  150. "remove requirement")
  151. class InstancemethodAttrTest(FuncAttrsTest):
  152. def test_im_class(self):
  153. self.assertEqual(self.f.a.im_class, self.f)
  154. self.assertEqual(self.fi.a.im_class, self.f)
  155. self.cannot_set_attr(self.f.a, "im_class", self.f, TypeError)
  156. self.cannot_set_attr(self.fi.a, "im_class", self.f, TypeError)
  157. def test_im_func(self):
  158. self.f.b = self.b
  159. self.assertEqual(self.f.b.im_func, self.b)
  160. self.assertEqual(self.fi.b.im_func, self.b)
  161. self.cannot_set_attr(self.f.b, "im_func", self.b, TypeError)
  162. self.cannot_set_attr(self.fi.b, "im_func", self.b, TypeError)
  163. def test_im_self(self):
  164. self.assertEqual(self.f.a.im_self, None)
  165. self.assertEqual(self.fi.a.im_self, self.fi)
  166. self.cannot_set_attr(self.f.a, "im_self", None, TypeError)
  167. self.cannot_set_attr(self.fi.a, "im_self", self.fi, TypeError)
  168. def test_im_func_non_method(self):
  169. # Behavior should be the same when a method is added via an attr
  170. # assignment
  171. self.f.id = types.MethodType(id, None, self.f)
  172. self.assertEqual(self.fi.id(), id(self.fi))
  173. self.assertNotEqual(self.fi.id(), id(self.f))
  174. # Test usage
  175. try:
  176. self.f.id.unknown_attr
  177. except AttributeError:
  178. pass
  179. else:
  180. self.fail("using unknown attributes should raise AttributeError")
  181. # Test assignment and deletion
  182. self.cannot_set_attr(self.f.id, 'unknown_attr', 2, AttributeError)
  183. self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError)
  184. def test_implicit_method_properties(self):
  185. self.f.a.im_func.known_attr = 7
  186. self.assertEqual(self.f.a.known_attr, 7)
  187. self.assertEqual(self.fi.a.known_attr, 7)
  188. class ArbitraryFunctionAttrTest(FuncAttrsTest):
  189. def test_set_attr(self):
  190. # setting attributes only works on function objects
  191. self.b.known_attr = 7
  192. self.assertEqual(self.b.known_attr, 7)
  193. for func in [self.f.a, self.fi.a]:
  194. try:
  195. func.known_attr = 7
  196. except AttributeError:
  197. pass
  198. else:
  199. self.fail("setting attributes on methods should raise error")
  200. def test_delete_unknown_attr(self):
  201. try:
  202. del self.b.unknown_attr
  203. except AttributeError:
  204. pass
  205. else:
  206. self.fail("deleting unknown attribute should raise TypeError")
  207. def test_setting_attrs_duplicates(self):
  208. try:
  209. self.f.a.klass = self.f
  210. except AttributeError:
  211. pass
  212. else:
  213. self.fail("setting arbitrary attribute in unbound function "
  214. " should raise AttributeError")
  215. self.f.a.im_func.klass = self.f
  216. for method in [self.f.a, self.fi.a, self.fi.a.im_func]:
  217. self.assertEqual(method.klass, self.f)
  218. def test_unset_attr(self):
  219. for func in [self.b, self.f.a, self.fi.a]:
  220. try:
  221. func.non_existent_attr
  222. except AttributeError:
  223. pass
  224. else:
  225. self.fail("using unknown attributes should raise "
  226. "AttributeError")
  227. class FunctionDictsTest(FuncAttrsTest):
  228. def test_setting_dict_to_invalid(self):
  229. self.cannot_set_attr(self.b, '__dict__', None, TypeError)
  230. self.cannot_set_attr(self.b, 'func_dict', None, TypeError)
  231. from UserDict import UserDict
  232. d = UserDict({'known_attr': 7})
  233. self.cannot_set_attr(self.f.a.im_func, '__dict__', d, TypeError)
  234. self.cannot_set_attr(self.fi.a.im_func, '__dict__', d, TypeError)
  235. def test_setting_dict_to_valid(self):
  236. d = {'known_attr': 7}
  237. self.b.__dict__ = d
  238. # Setting dict is only possible on the underlying function objects
  239. self.f.a.im_func.__dict__ = d
  240. # Test assignment
  241. self.assertIs(d, self.b.__dict__)
  242. self.assertIs(d, self.b.func_dict)
  243. # ... and on all the different ways of referencing the method's func
  244. self.assertIs(d, self.f.a.im_func.__dict__)
  245. self.assertIs(d, self.f.a.__dict__)
  246. self.assertIs(d, self.fi.a.im_func.__dict__)
  247. self.assertIs(d, self.fi.a.__dict__)
  248. # Test value
  249. self.assertEqual(self.b.known_attr, 7)
  250. self.assertEqual(self.b.__dict__['known_attr'], 7)
  251. self.assertEqual(self.b.func_dict['known_attr'], 7)
  252. # ... and again, on all the different method's names
  253. self.assertEqual(self.f.a.im_func.known_attr, 7)
  254. self.assertEqual(self.f.a.known_attr, 7)
  255. self.assertEqual(self.fi.a.im_func.known_attr, 7)
  256. self.assertEqual(self.fi.a.known_attr, 7)
  257. def test_delete_func_dict(self):
  258. try:
  259. del self.b.__dict__
  260. except TypeError:
  261. pass
  262. else:
  263. self.fail("deleting function dictionary should raise TypeError")
  264. try:
  265. del self.b.func_dict
  266. except TypeError:
  267. pass
  268. else:
  269. self.fail("deleting function dictionary should raise TypeError")
  270. def test_unassigned_dict(self):
  271. self.assertEqual(self.b.__dict__, {})
  272. def test_func_as_dict_key(self):
  273. value = "Some string"
  274. d = {}
  275. d[self.b] = value
  276. self.assertEqual(d[self.b], value)
  277. class FunctionDocstringTest(FuncAttrsTest):
  278. def test_set_docstring_attr(self):
  279. self.assertEqual(self.b.__doc__, None)
  280. self.assertEqual(self.b.func_doc, None)
  281. docstr = "A test method that does nothing"
  282. self.b.__doc__ = self.f.a.im_func.__doc__ = docstr
  283. self.assertEqual(self.b.__doc__, docstr)
  284. self.assertEqual(self.b.func_doc, docstr)
  285. self.assertEqual(self.f.a.__doc__, docstr)
  286. self.assertEqual(self.fi.a.__doc__, docstr)
  287. self.cannot_set_attr(self.f.a, "__doc__", docstr, AttributeError)
  288. self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError)
  289. def test_delete_docstring(self):
  290. self.b.__doc__ = "The docstring"
  291. del self.b.__doc__
  292. self.assertEqual(self.b.__doc__, None)
  293. self.assertEqual(self.b.func_doc, None)
  294. self.b.func_doc = "The docstring"
  295. del self.b.func_doc
  296. self.assertEqual(self.b.__doc__, None)
  297. self.assertEqual(self.b.func_doc, None)
  298. class StaticMethodAttrsTest(unittest.TestCase):
  299. def test_func_attribute(self):
  300. def f():
  301. pass
  302. c = classmethod(f)
  303. self.assertTrue(c.__func__ is f)
  304. s = staticmethod(f)
  305. self.assertTrue(s.__func__ is f)
  306. def test_main():
  307. test_support.run_unittest(FunctionPropertiesTest, InstancemethodAttrTest,
  308. ArbitraryFunctionAttrTest, FunctionDictsTest,
  309. FunctionDocstringTest,
  310. StaticMethodAttrsTest)
  311. if __name__ == "__main__":
  312. test_main()