/Lib/test/test_py3kwarn.py

http://unladen-swallow.googlecode.com/ · Python · 412 lines · 352 code · 42 blank · 18 comment · 46 complexity · aa43de95226037cac6c5028aab4ec7b9 MD5 · raw file

  1. import unittest
  2. import sys
  3. from test.test_support import (check_warnings, CleanImport,
  4. TestSkipped, run_unittest)
  5. import warnings
  6. from contextlib import nested
  7. if not sys.py3kwarning:
  8. raise TestSkipped('%s must be run with the -3 flag' % __name__)
  9. def reset_module_registry(module):
  10. try:
  11. registry = module.__warningregistry__
  12. except AttributeError:
  13. pass
  14. else:
  15. registry.clear()
  16. class TestPy3KWarnings(unittest.TestCase):
  17. def assertWarning(self, _, warning, expected_message):
  18. self.assertEqual(str(warning.message), expected_message)
  19. def assertNoWarning(self, _, recorder):
  20. self.assertEqual(len(recorder.warnings), 0)
  21. def test_backquote(self):
  22. expected = 'backquote not supported in 3.x; use repr()'
  23. with check_warnings() as w:
  24. exec "`2`" in {}
  25. self.assertWarning(None, w, expected)
  26. def test_bool_assign(self):
  27. # So we don't screw up our globals
  28. def safe_exec(expr):
  29. def f(**kwargs): pass
  30. exec expr in {'f' : f}
  31. expected = "assignment to True or False is forbidden in 3.x"
  32. with check_warnings() as w:
  33. safe_exec("True = False")
  34. self.assertWarning(None, w, expected)
  35. w.reset()
  36. safe_exec("False = True")
  37. self.assertWarning(None, w, expected)
  38. w.reset()
  39. try:
  40. safe_exec("obj.False = True")
  41. except NameError: pass
  42. self.assertWarning(None, w, expected)
  43. w.reset()
  44. try:
  45. safe_exec("obj.True = False")
  46. except NameError: pass
  47. self.assertWarning(None, w, expected)
  48. w.reset()
  49. safe_exec("def False(): pass")
  50. self.assertWarning(None, w, expected)
  51. w.reset()
  52. safe_exec("def True(): pass")
  53. self.assertWarning(None, w, expected)
  54. w.reset()
  55. safe_exec("class False: pass")
  56. self.assertWarning(None, w, expected)
  57. w.reset()
  58. safe_exec("class True: pass")
  59. self.assertWarning(None, w, expected)
  60. w.reset()
  61. safe_exec("def f(True=43): pass")
  62. self.assertWarning(None, w, expected)
  63. w.reset()
  64. safe_exec("def f(False=None): pass")
  65. self.assertWarning(None, w, expected)
  66. w.reset()
  67. safe_exec("f(False=True)")
  68. self.assertWarning(None, w, expected)
  69. w.reset()
  70. safe_exec("f(True=1)")
  71. self.assertWarning(None, w, expected)
  72. def test_type_inequality_comparisons(self):
  73. expected = 'type inequality comparisons not supported in 3.x'
  74. with check_warnings() as w:
  75. self.assertWarning(int < str, w, expected)
  76. w.reset()
  77. self.assertWarning(type < object, w, expected)
  78. def test_object_inequality_comparisons(self):
  79. expected = 'comparing unequal types not supported in 3.x'
  80. with check_warnings() as w:
  81. self.assertWarning(str < [], w, expected)
  82. w.reset()
  83. self.assertWarning(object() < (1, 2), w, expected)
  84. def test_dict_inequality_comparisons(self):
  85. expected = 'dict inequality comparisons not supported in 3.x'
  86. with check_warnings() as w:
  87. self.assertWarning({} < {2:3}, w, expected)
  88. w.reset()
  89. self.assertWarning({} <= {}, w, expected)
  90. w.reset()
  91. self.assertWarning({} > {2:3}, w, expected)
  92. w.reset()
  93. self.assertWarning({2:3} >= {}, w, expected)
  94. def test_cell_inequality_comparisons(self):
  95. expected = 'cell comparisons not supported in 3.x'
  96. def f(x):
  97. def g():
  98. return x
  99. return g
  100. cell0, = f(0).func_closure
  101. cell1, = f(1).func_closure
  102. with check_warnings() as w:
  103. self.assertWarning(cell0 == cell1, w, expected)
  104. w.reset()
  105. self.assertWarning(cell0 < cell1, w, expected)
  106. def test_code_inequality_comparisons(self):
  107. expected = 'code inequality comparisons not supported in 3.x'
  108. def f(x):
  109. pass
  110. def g(x):
  111. pass
  112. with check_warnings() as w:
  113. self.assertWarning(f.func_code < g.func_code, w, expected)
  114. w.reset()
  115. self.assertWarning(f.func_code <= g.func_code, w, expected)
  116. w.reset()
  117. self.assertWarning(f.func_code >= g.func_code, w, expected)
  118. w.reset()
  119. self.assertWarning(f.func_code > g.func_code, w, expected)
  120. def test_builtin_function_or_method_comparisons(self):
  121. expected = ('builtin_function_or_method '
  122. 'order comparisons not supported in 3.x')
  123. func = eval
  124. meth = {}.get
  125. with check_warnings() as w:
  126. self.assertWarning(func < meth, w, expected)
  127. w.reset()
  128. self.assertWarning(func > meth, w, expected)
  129. w.reset()
  130. self.assertWarning(meth <= func, w, expected)
  131. w.reset()
  132. self.assertWarning(meth >= func, w, expected)
  133. w.reset()
  134. self.assertNoWarning(meth == func, w)
  135. self.assertNoWarning(meth != func, w)
  136. lam = lambda x: x
  137. self.assertNoWarning(lam == func, w)
  138. self.assertNoWarning(lam != func, w)
  139. def test_sort_cmp_arg(self):
  140. expected = "the cmp argument is not supported in 3.x"
  141. lst = range(5)
  142. cmp = lambda x,y: -1
  143. with check_warnings() as w:
  144. self.assertWarning(lst.sort(cmp=cmp), w, expected)
  145. w.reset()
  146. self.assertWarning(sorted(lst, cmp=cmp), w, expected)
  147. w.reset()
  148. self.assertWarning(lst.sort(cmp), w, expected)
  149. w.reset()
  150. self.assertWarning(sorted(lst, cmp), w, expected)
  151. def test_sys_exc_clear(self):
  152. expected = 'sys.exc_clear() not supported in 3.x; use except clauses'
  153. with check_warnings() as w:
  154. self.assertWarning(sys.exc_clear(), w, expected)
  155. def test_methods_members(self):
  156. expected = '__members__ and __methods__ not supported in 3.x'
  157. class C:
  158. __methods__ = ['a']
  159. __members__ = ['b']
  160. c = C()
  161. with check_warnings() as w:
  162. self.assertWarning(dir(c), w, expected)
  163. def test_softspace(self):
  164. expected = 'file.softspace not supported in 3.x'
  165. with file(__file__) as f:
  166. with check_warnings() as w:
  167. self.assertWarning(f.softspace, w, expected)
  168. def set():
  169. f.softspace = 0
  170. with check_warnings() as w:
  171. self.assertWarning(set(), w, expected)
  172. def test_slice_methods(self):
  173. class Spam(object):
  174. def __getslice__(self, i, j): pass
  175. def __setslice__(self, i, j, what): pass
  176. def __delslice__(self, i, j): pass
  177. class Egg:
  178. def __getslice__(self, i, h): pass
  179. def __setslice__(self, i, j, what): pass
  180. def __delslice__(self, i, j): pass
  181. expected = "in 3.x, __{0}slice__ has been removed; use __{0}item__"
  182. for obj in (Spam(), Egg()):
  183. with check_warnings() as w:
  184. self.assertWarning(obj[1:2], w, expected.format('get'))
  185. w.reset()
  186. del obj[3:4]
  187. self.assertWarning(None, w, expected.format('del'))
  188. w.reset()
  189. obj[4:5] = "eggs"
  190. self.assertWarning(None, w, expected.format('set'))
  191. def test_tuple_parameter_unpacking(self):
  192. expected = "tuple parameter unpacking has been removed in 3.x"
  193. with check_warnings() as w:
  194. exec "def f((a, b)): pass"
  195. self.assertWarning(None, w, expected)
  196. def test_buffer(self):
  197. expected = 'buffer() not supported in 3.x'
  198. with check_warnings() as w:
  199. self.assertWarning(buffer('a'), w, expected)
  200. def test_file_xreadlines(self):
  201. expected = ("f.xreadlines() not supported in 3.x, "
  202. "try 'for line in f' instead")
  203. with file(__file__) as f:
  204. with check_warnings() as w:
  205. self.assertWarning(f.xreadlines(), w, expected)
  206. def test_hash_inheritance(self):
  207. with check_warnings() as w:
  208. # With object as the base class
  209. class WarnOnlyCmp(object):
  210. def __cmp__(self, other): pass
  211. self.assertEqual(len(w.warnings), 1)
  212. self.assertWarning(None, w,
  213. "Overriding __cmp__ blocks inheritance of __hash__ in 3.x")
  214. w.reset()
  215. class WarnOnlyEq(object):
  216. def __eq__(self, other): pass
  217. self.assertEqual(len(w.warnings), 1)
  218. self.assertWarning(None, w,
  219. "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
  220. w.reset()
  221. class WarnCmpAndEq(object):
  222. def __cmp__(self, other): pass
  223. def __eq__(self, other): pass
  224. self.assertEqual(len(w.warnings), 2)
  225. self.assertWarning(None, w.warnings[0],
  226. "Overriding __cmp__ blocks inheritance of __hash__ in 3.x")
  227. self.assertWarning(None, w,
  228. "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
  229. w.reset()
  230. class NoWarningOnlyHash(object):
  231. def __hash__(self): pass
  232. self.assertEqual(len(w.warnings), 0)
  233. # With an intermediate class in the heirarchy
  234. class DefinesAllThree(object):
  235. def __cmp__(self, other): pass
  236. def __eq__(self, other): pass
  237. def __hash__(self): pass
  238. class WarnOnlyCmp(DefinesAllThree):
  239. def __cmp__(self, other): pass
  240. self.assertEqual(len(w.warnings), 1)
  241. self.assertWarning(None, w,
  242. "Overriding __cmp__ blocks inheritance of __hash__ in 3.x")
  243. w.reset()
  244. class WarnOnlyEq(DefinesAllThree):
  245. def __eq__(self, other): pass
  246. self.assertEqual(len(w.warnings), 1)
  247. self.assertWarning(None, w,
  248. "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
  249. w.reset()
  250. class WarnCmpAndEq(DefinesAllThree):
  251. def __cmp__(self, other): pass
  252. def __eq__(self, other): pass
  253. self.assertEqual(len(w.warnings), 2)
  254. self.assertWarning(None, w.warnings[0],
  255. "Overriding __cmp__ blocks inheritance of __hash__ in 3.x")
  256. self.assertWarning(None, w,
  257. "Overriding __eq__ blocks inheritance of __hash__ in 3.x")
  258. w.reset()
  259. class NoWarningOnlyHash(DefinesAllThree):
  260. def __hash__(self): pass
  261. self.assertEqual(len(w.warnings), 0)
  262. class TestStdlibRemovals(unittest.TestCase):
  263. # test.testall not tested as it executes all unit tests as an
  264. # import side-effect.
  265. all_platforms = ('audiodev', 'imputil', 'mutex', 'user', 'new', 'rexec',
  266. 'Bastion', 'compiler', 'dircache', 'mimetools',
  267. 'fpformat', 'ihooks', 'mhlib', 'statvfs', 'htmllib',
  268. 'sgmllib', 'rfc822', 'sunaudio')
  269. inclusive_platforms = {'irix' : ('pure', 'AL', 'al', 'CD', 'cd', 'cddb',
  270. 'cdplayer', 'CL', 'cl', 'DEVICE', 'GL',
  271. 'gl', 'ERRNO', 'FILE', 'FL', 'flp', 'fl',
  272. 'fm', 'GET', 'GLWS', 'imgfile', 'IN',
  273. 'IOCTL', 'jpeg', 'panel', 'panelparser',
  274. 'readcd', 'SV', 'torgb', 'WAIT'),
  275. 'darwin' : ('autoGIL', 'Carbon', 'OSATerminology',
  276. 'icglue', 'Nav', 'MacOS', 'aepack',
  277. 'aetools', 'aetypes', 'applesingle',
  278. 'appletrawmain', 'appletrunner',
  279. 'argvemulator', 'bgenlocations',
  280. 'EasyDialogs', 'macerrors', 'macostools',
  281. 'findertools', 'FrameWork', 'ic',
  282. 'gensuitemodule', 'icopen', 'macresource',
  283. 'MiniAEFrame', 'pimp', 'PixMapWrapper',
  284. 'terminalcommand', 'videoreader',
  285. '_builtinSuites', 'CodeWarrior',
  286. 'Explorer', 'Finder', 'Netscape',
  287. 'StdSuites', 'SystemEvents', 'Terminal',
  288. 'cfmfile', 'bundlebuilder', 'buildtools',
  289. 'ColorPicker', 'Audio_mac'),
  290. 'sunos5' : ('sunaudiodev', 'SUNAUDIODEV'),
  291. }
  292. optional_modules = ('bsddb185', 'Canvas', 'dl', 'linuxaudiodev', 'imageop',
  293. 'sv', 'cPickle', 'bsddb', 'dbhash')
  294. def check_removal(self, module_name, optional=False):
  295. """Make sure the specified module, when imported, raises a
  296. DeprecationWarning and specifies itself in the message."""
  297. with nested(CleanImport(module_name), warnings.catch_warnings()):
  298. # XXX: This is not quite enough for extension modules - those
  299. # won't rerun their init code even with CleanImport.
  300. # You can see this easily by running the whole test suite with -3
  301. warnings.filterwarnings("error", ".+ removed",
  302. DeprecationWarning, __name__)
  303. try:
  304. __import__(module_name, level=0)
  305. except DeprecationWarning as exc:
  306. self.assert_(module_name in exc.args[0],
  307. "%s warning didn't contain module name"
  308. % module_name)
  309. except ImportError:
  310. if not optional:
  311. self.fail("Non-optional module {0} raised an "
  312. "ImportError.".format(module_name))
  313. else:
  314. self.fail("DeprecationWarning not raised for {0}"
  315. .format(module_name))
  316. def test_platform_independent_removals(self):
  317. # Make sure that the modules that are available on all platforms raise
  318. # the proper DeprecationWarning.
  319. for module_name in self.all_platforms:
  320. self.check_removal(module_name)
  321. def test_platform_specific_removals(self):
  322. # Test the removal of platform-specific modules.
  323. for module_name in self.inclusive_platforms.get(sys.platform, []):
  324. self.check_removal(module_name, optional=True)
  325. def test_optional_module_removals(self):
  326. # Test the removal of modules that may or may not be built.
  327. for module_name in self.optional_modules:
  328. self.check_removal(module_name, optional=True)
  329. def test_os_path_walk(self):
  330. msg = "In 3.x, os.path.walk is removed in favor of os.walk."
  331. def dumbo(where, names, args): pass
  332. for path_mod in ("ntpath", "macpath", "os2emxpath", "posixpath"):
  333. mod = __import__(path_mod)
  334. reset_module_registry(mod)
  335. with check_warnings() as w:
  336. mod.walk("crashers", dumbo, None)
  337. self.assertEquals(str(w.message), msg)
  338. def test_commands_members(self):
  339. import commands
  340. # commands module tests may have already triggered this warning
  341. reset_module_registry(commands)
  342. members = {"mk2arg" : 2, "mkarg" : 1, "getstatus" : 1}
  343. for name, arg_count in members.items():
  344. with warnings.catch_warnings():
  345. warnings.filterwarnings("error")
  346. func = getattr(commands, name)
  347. self.assertRaises(DeprecationWarning, func, *([None]*arg_count))
  348. def test_reduce_move(self):
  349. from operator import add
  350. # reduce tests may have already triggered this warning
  351. reset_module_registry(unittest)
  352. with warnings.catch_warnings():
  353. warnings.filterwarnings("error", "reduce")
  354. self.assertRaises(DeprecationWarning, reduce, add, range(10))
  355. def test_mutablestring_removal(self):
  356. # UserString.MutableString has been removed in 3.0.
  357. import UserString
  358. # UserString tests may have already triggered this warning
  359. reset_module_registry(UserString)
  360. with warnings.catch_warnings():
  361. warnings.filterwarnings("error", ".*MutableString",
  362. DeprecationWarning)
  363. self.assertRaises(DeprecationWarning, UserString.MutableString)
  364. def test_main():
  365. with check_warnings():
  366. warnings.simplefilter("always")
  367. run_unittest(TestPy3KWarnings,
  368. TestStdlibRemovals)
  369. if __name__ == '__main__':
  370. test_main()