/Lib/test/test_funcattrs.py

http://unladen-swallow.googlecode.com/ · Python · 282 lines · 233 code · 30 blank · 19 comment · 41 complexity · 3512f058d8ad358e964385ac4480c570 MD5 · raw file

  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. # This method is not called as a test (name doesn't start with 'test'),
  16. # but may be used by other tests.
  17. try: setattr(obj, name, value)
  18. except exceptions: pass
  19. else: self.fail("shouldn't be able to set %s to %r" % (name, value))
  20. try: delattr(obj, name)
  21. except exceptions: pass
  22. else: self.fail("shouldn't be able to del %s" % name)
  23. class FunctionPropertiesTest(FuncAttrsTest):
  24. # Include the external setUp method that is common to all tests
  25. def test_module(self):
  26. self.assertEqual(self.b.__module__, __name__)
  27. def test_dir_includes_correct_attrs(self):
  28. self.b.known_attr = 7
  29. self.assert_('known_attr' in dir(self.b),
  30. "set attributes not in dir listing of method")
  31. # Test on underlying function object of method
  32. self.f.a.im_func.known_attr = 7
  33. self.assert_('known_attr' in dir(self.f.a),
  34. "set attribute on unbound method implementation in class not in "
  35. "dir")
  36. self.assert_('known_attr' in dir(self.fi.a),
  37. "set attribute on unbound method implementations, should show up"
  38. " in next dir")
  39. def test_duplicate_function_equality(self):
  40. # Body of `duplicate' is the exact same as self.b
  41. def duplicate():
  42. 'my docstring'
  43. return 3
  44. self.assertNotEqual(self.b, duplicate)
  45. def test_copying_func_code(self):
  46. def test(): pass
  47. self.assertEqual(test(), None)
  48. test.func_code = self.b.func_code
  49. self.assertEqual(test(), 3) # self.b always returns 3, arbitrarily
  50. def test_func_globals(self):
  51. self.assertEqual(self.b.func_globals, globals())
  52. self.cannot_set_attr(self.b, 'func_globals', 2, TypeError)
  53. def test_func_name(self):
  54. self.assertEqual(self.b.__name__, 'b')
  55. self.assertEqual(self.b.func_name, 'b')
  56. self.b.__name__ = 'c'
  57. self.assertEqual(self.b.__name__, 'c')
  58. self.assertEqual(self.b.func_name, 'c')
  59. self.b.func_name = 'd'
  60. self.assertEqual(self.b.__name__, 'd')
  61. self.assertEqual(self.b.func_name, 'd')
  62. # __name__ and func_name must be a string
  63. self.cannot_set_attr(self.b, '__name__', 7, TypeError)
  64. self.cannot_set_attr(self.b, 'func_name', 7, TypeError)
  65. # __name__ must be available when in restricted mode. Exec will raise
  66. # AttributeError if __name__ is not available on f.
  67. s = """def f(): pass\nf.__name__"""
  68. exec s in {'__builtins__': {}}
  69. # Test on methods, too
  70. self.assertEqual(self.f.a.__name__, 'a')
  71. self.assertEqual(self.fi.a.__name__, 'a')
  72. self.cannot_set_attr(self.f.a, "__name__", 'a', AttributeError)
  73. self.cannot_set_attr(self.fi.a, "__name__", 'a', AttributeError)
  74. def test_func_code(self):
  75. num_one, num_two = 7, 8
  76. def a(): pass
  77. def b(): return 12
  78. def c(): return num_one
  79. def d(): return num_two
  80. def e(): return num_one, num_two
  81. for func in [a, b, c, d, e]:
  82. self.assertEqual(type(func.func_code), types.CodeType)
  83. self.assertEqual(c(), 7)
  84. self.assertEqual(d(), 8)
  85. d.func_code = c.func_code
  86. self.assertEqual(c.func_code, d.func_code)
  87. self.assertEqual(c(), 7)
  88. # self.assertEqual(d(), 7)
  89. try: b.func_code = c.func_code
  90. except ValueError: pass
  91. else: self.fail(
  92. "func_code with different numbers of free vars should not be "
  93. "possible")
  94. try: e.func_code = d.func_code
  95. except ValueError: pass
  96. else: self.fail(
  97. "func_code with different numbers of free vars should not be "
  98. "possible")
  99. def test_blank_func_defaults(self):
  100. self.assertEqual(self.b.func_defaults, None)
  101. del self.b.func_defaults
  102. self.assertEqual(self.b.func_defaults, None)
  103. def test_func_default_args(self):
  104. def first_func(a, b):
  105. return a+b
  106. def second_func(a=1, b=2):
  107. return a+b
  108. self.assertEqual(first_func.func_defaults, None)
  109. self.assertEqual(second_func.func_defaults, (1, 2))
  110. first_func.func_defaults = (1, 2)
  111. self.assertEqual(first_func.func_defaults, (1, 2))
  112. self.assertEqual(first_func(), 3)
  113. self.assertEqual(first_func(3), 5)
  114. self.assertEqual(first_func(3, 5), 8)
  115. del second_func.func_defaults
  116. self.assertEqual(second_func.func_defaults, None)
  117. try: second_func()
  118. except TypeError: pass
  119. else: self.fail(
  120. "func_defaults does not update; deleting it does not remove "
  121. "requirement")
  122. class ImplicitReferencesTest(FuncAttrsTest):
  123. def test_im_class(self):
  124. self.assertEqual(self.f.a.im_class, self.f)
  125. self.assertEqual(self.fi.a.im_class, self.f)
  126. self.cannot_set_attr(self.f.a, "im_class", self.f, TypeError)
  127. self.cannot_set_attr(self.fi.a, "im_class", self.f, TypeError)
  128. def test_im_func(self):
  129. self.f.b = self.b
  130. self.assertEqual(self.f.b.im_func, self.b)
  131. self.assertEqual(self.fi.b.im_func, self.b)
  132. self.cannot_set_attr(self.f.b, "im_func", self.b, TypeError)
  133. self.cannot_set_attr(self.fi.b, "im_func", self.b, TypeError)
  134. def test_im_self(self):
  135. self.assertEqual(self.f.a.im_self, None)
  136. self.assertEqual(self.fi.a.im_self, self.fi)
  137. self.cannot_set_attr(self.f.a, "im_self", None, TypeError)
  138. self.cannot_set_attr(self.fi.a, "im_self", self.fi, TypeError)
  139. def test_im_func_non_method(self):
  140. # Behavior should be the same when a method is added via an attr
  141. # assignment
  142. self.f.id = types.MethodType(id, None, self.f)
  143. self.assertEqual(self.fi.id(), id(self.fi))
  144. self.assertNotEqual(self.fi.id(), id(self.f))
  145. # Test usage
  146. try: self.f.id.unknown_attr
  147. except AttributeError: pass
  148. else: self.fail("using unknown attributes should raise AttributeError")
  149. # Test assignment and deletion
  150. self.cannot_set_attr(self.f.id, 'unknown_attr', 2, AttributeError)
  151. self.cannot_set_attr(self.fi.id, 'unknown_attr', 2, AttributeError)
  152. def test_implicit_method_properties(self):
  153. self.f.a.im_func.known_attr = 7
  154. self.assertEqual(self.f.a.known_attr, 7)
  155. self.assertEqual(self.fi.a.known_attr, 7)
  156. class ArbitraryFunctionAttrTest(FuncAttrsTest):
  157. def test_set_attr(self):
  158. self.b.known_attr = 7
  159. self.assertEqual(self.b.known_attr, 7)
  160. for func in [self.f.a, self.fi.a]:
  161. try: func.known_attr = 7
  162. except AttributeError: pass
  163. else: self.fail("setting attributes on methods should raise error")
  164. def test_delete_unknown_attr(self):
  165. try: del self.b.unknown_attr
  166. except AttributeError: pass
  167. else: self.fail("deleting unknown attribute should raise TypeError")
  168. def test_setting_attrs_duplicates(self):
  169. try: self.f.a.klass = self.f
  170. except AttributeError: pass
  171. else: self.fail("setting arbitrary attribute in unbound function "
  172. " should raise AttributeError")
  173. self.f.a.im_func.klass = self.f
  174. for method in [self.f.a, self.fi.a, self.fi.a.im_func]:
  175. self.assertEqual(method.klass, self.f)
  176. def test_unset_attr(self):
  177. for func in [self.b, self.f.a, self.fi.a]:
  178. try: func.non_existent_attr
  179. except AttributeError: pass
  180. else: self.fail("using unknown attributes should raise "
  181. "AttributeError")
  182. class FunctionDictsTest(FuncAttrsTest):
  183. def test_setting_dict_to_invalid(self):
  184. self.cannot_set_attr(self.b, '__dict__', None, TypeError)
  185. self.cannot_set_attr(self.b, 'func_dict', None, TypeError)
  186. from UserDict import UserDict
  187. d = UserDict({'known_attr': 7})
  188. self.cannot_set_attr(self.f.a.im_func, '__dict__', d, TypeError)
  189. self.cannot_set_attr(self.fi.a.im_func, '__dict__', d, TypeError)
  190. def test_setting_dict_to_valid(self):
  191. d = {'known_attr': 7}
  192. self.b.__dict__ = d
  193. # Setting dict is only possible on the underlying function objects
  194. self.f.a.im_func.__dict__ = d
  195. # Test assignment
  196. self.assertEqual(d, self.b.__dict__)
  197. self.assertEqual(d, self.b.func_dict)
  198. # ... and on all the different ways of referencing the method's func
  199. self.assertEqual(d, self.f.a.im_func.__dict__)
  200. self.assertEqual(d, self.f.a.__dict__)
  201. self.assertEqual(d, self.fi.a.im_func.__dict__)
  202. self.assertEqual(d, self.fi.a.__dict__)
  203. # Test value
  204. self.assertEqual(self.b.known_attr, 7)
  205. self.assertEqual(self.b.__dict__['known_attr'], 7)
  206. self.assertEqual(self.b.func_dict['known_attr'], 7)
  207. # ... and again, on all the different method's names
  208. self.assertEqual(self.f.a.im_func.known_attr, 7)
  209. self.assertEqual(self.f.a.known_attr, 7)
  210. self.assertEqual(self.fi.a.im_func.known_attr, 7)
  211. self.assertEqual(self.fi.a.known_attr, 7)
  212. def test_delete_func_dict(self):
  213. try: del self.b.__dict__
  214. except TypeError: pass
  215. else: self.fail("deleting function dictionary should raise TypeError")
  216. try: del self.b.func_dict
  217. except TypeError: pass
  218. else: self.fail("deleting function dictionary should raise TypeError")
  219. def test_unassigned_dict(self):
  220. self.assertEqual(self.b.__dict__, {})
  221. def test_func_as_dict_key(self):
  222. value = "Some string"
  223. d = {}
  224. d[self.b] = value
  225. self.assertEqual(d[self.b], value)
  226. class FunctionDocstringTest(FuncAttrsTest):
  227. def test_set_docstring_attr(self):
  228. self.assertEqual(self.b.__doc__, None)
  229. self.assertEqual(self.b.func_doc, None)
  230. docstr = "A test method that does nothing"
  231. self.b.__doc__ = self.f.a.im_func.__doc__ = docstr
  232. self.assertEqual(self.b.__doc__, docstr)
  233. self.assertEqual(self.b.func_doc, docstr)
  234. self.assertEqual(self.f.a.__doc__, docstr)
  235. self.assertEqual(self.fi.a.__doc__, docstr)
  236. self.cannot_set_attr(self.f.a, "__doc__", docstr, AttributeError)
  237. self.cannot_set_attr(self.fi.a, "__doc__", docstr, AttributeError)
  238. def test_delete_docstring(self):
  239. self.b.__doc__ = "The docstring"
  240. del self.b.__doc__
  241. self.assertEqual(self.b.__doc__, None)
  242. self.assertEqual(self.b.func_doc, None)
  243. self.b.func_doc = "The docstring"
  244. del self.b.func_doc
  245. self.assertEqual(self.b.__doc__, None)
  246. self.assertEqual(self.b.func_doc, None)
  247. def test_main():
  248. test_support.run_unittest(FunctionPropertiesTest, ImplicitReferencesTest,
  249. ArbitraryFunctionAttrTest, FunctionDictsTest,
  250. FunctionDocstringTest)
  251. if __name__ == "__main__":
  252. test_main()