test_warning.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for Trial's interaction with the Python warning system.
  5. """
  6. from __future__ import division, absolute_import
  7. import sys, warnings
  8. from unittest import TestResult
  9. from twisted.python.compat import NativeStringIO as StringIO
  10. from twisted.python.filepath import FilePath
  11. from twisted.trial.unittest import SynchronousTestCase
  12. from twisted.trial._synctest import _collectWarnings, _setWarningRegistryToNone
  13. class Mask(object):
  14. """
  15. Hide a test case definition from trial's automatic discovery mechanism.
  16. """
  17. class MockTests(SynchronousTestCase):
  18. """
  19. A test case which is used by L{FlushWarningsTests} to verify behavior
  20. which cannot be verified by code inside a single test method.
  21. """
  22. message = "some warning text"
  23. category = UserWarning
  24. def test_unflushed(self):
  25. """
  26. Generate a warning and don't flush it.
  27. """
  28. warnings.warn(self.message, self.category)
  29. def test_flushed(self):
  30. """
  31. Generate a warning and flush it.
  32. """
  33. warnings.warn(self.message, self.category)
  34. self.assertEqual(len(self.flushWarnings()), 1)
  35. class FlushWarningsTests(SynchronousTestCase):
  36. """
  37. Tests for C{flushWarnings}, an API for examining the warnings
  38. emitted so far in a test.
  39. """
  40. def assertDictSubset(self, set, subset):
  41. """
  42. Assert that all the keys present in C{subset} are also present in
  43. C{set} and that the corresponding values are equal.
  44. """
  45. for k, v in subset.items():
  46. self.assertEqual(set[k], v)
  47. def assertDictSubsets(self, sets, subsets):
  48. """
  49. For each pair of corresponding elements in C{sets} and C{subsets},
  50. assert that the element from C{subsets} is a subset of the element from
  51. C{sets}.
  52. """
  53. self.assertEqual(len(sets), len(subsets))
  54. for a, b in zip(sets, subsets):
  55. self.assertDictSubset(a, b)
  56. def test_none(self):
  57. """
  58. If no warnings are emitted by a test, C{flushWarnings} returns an empty
  59. list.
  60. """
  61. self.assertEqual(self.flushWarnings(), [])
  62. def test_several(self):
  63. """
  64. If several warnings are emitted by a test, C{flushWarnings} returns a
  65. list containing all of them.
  66. """
  67. firstMessage = "first warning message"
  68. firstCategory = UserWarning
  69. warnings.warn(message=firstMessage, category=firstCategory)
  70. secondMessage = "second warning message"
  71. secondCategory = RuntimeWarning
  72. warnings.warn(message=secondMessage, category=secondCategory)
  73. self.assertDictSubsets(
  74. self.flushWarnings(),
  75. [{'category': firstCategory, 'message': firstMessage},
  76. {'category': secondCategory, 'message': secondMessage}])
  77. def test_repeated(self):
  78. """
  79. The same warning triggered twice from the same place is included twice
  80. in the list returned by C{flushWarnings}.
  81. """
  82. message = "the message"
  83. category = RuntimeWarning
  84. for i in range(2):
  85. warnings.warn(message=message, category=category)
  86. self.assertDictSubsets(
  87. self.flushWarnings(),
  88. [{'category': category, 'message': message}] * 2)
  89. def test_cleared(self):
  90. """
  91. After a particular warning event has been returned by C{flushWarnings},
  92. it is not returned by subsequent calls.
  93. """
  94. message = "the message"
  95. category = RuntimeWarning
  96. warnings.warn(message=message, category=category)
  97. self.assertDictSubsets(
  98. self.flushWarnings(),
  99. [{'category': category, 'message': message}])
  100. self.assertEqual(self.flushWarnings(), [])
  101. def test_unflushed(self):
  102. """
  103. Any warnings emitted by a test which are not flushed are emitted to the
  104. Python warning system.
  105. """
  106. result = TestResult()
  107. case = Mask.MockTests('test_unflushed')
  108. case.run(result)
  109. warningsShown = self.flushWarnings([Mask.MockTests.test_unflushed])
  110. self.assertEqual(warningsShown[0]['message'], 'some warning text')
  111. self.assertIdentical(warningsShown[0]['category'], UserWarning)
  112. where = type(case).test_unflushed.__code__
  113. filename = where.co_filename
  114. # If someone edits MockTests.test_unflushed, the value added to
  115. # firstlineno might need to change.
  116. lineno = where.co_firstlineno + 4
  117. self.assertEqual(warningsShown[0]['filename'], filename)
  118. self.assertEqual(warningsShown[0]['lineno'], lineno)
  119. self.assertEqual(len(warningsShown), 1)
  120. def test_flushed(self):
  121. """
  122. Any warnings emitted by a test which are flushed are not emitted to the
  123. Python warning system.
  124. """
  125. result = TestResult()
  126. case = Mask.MockTests('test_flushed')
  127. output = StringIO()
  128. monkey = self.patch(sys, 'stdout', output)
  129. case.run(result)
  130. monkey.restore()
  131. self.assertEqual(output.getvalue(), "")
  132. def test_warningsConfiguredAsErrors(self):
  133. """
  134. If a warnings filter has been installed which turns warnings into
  135. exceptions, tests have an error added to the reporter for them for each
  136. unflushed warning.
  137. """
  138. class CustomWarning(Warning):
  139. pass
  140. result = TestResult()
  141. case = Mask.MockTests('test_unflushed')
  142. case.category = CustomWarning
  143. originalWarnings = warnings.filters[:]
  144. try:
  145. warnings.simplefilter('error')
  146. case.run(result)
  147. self.assertEqual(len(result.errors), 1)
  148. self.assertIdentical(result.errors[0][0], case)
  149. self.assertTrue(
  150. # Different python versions differ in whether they report the
  151. # fully qualified class name or just the class name.
  152. result.errors[0][1].splitlines()[-1].endswith(
  153. "CustomWarning: some warning text"))
  154. finally:
  155. warnings.filters[:] = originalWarnings
  156. def test_flushedWarningsConfiguredAsErrors(self):
  157. """
  158. If a warnings filter has been installed which turns warnings into
  159. exceptions, tests which emit those warnings but flush them do not have
  160. an error added to the reporter.
  161. """
  162. class CustomWarning(Warning):
  163. pass
  164. result = TestResult()
  165. case = Mask.MockTests('test_flushed')
  166. case.category = CustomWarning
  167. originalWarnings = warnings.filters[:]
  168. try:
  169. warnings.simplefilter('error')
  170. case.run(result)
  171. self.assertEqual(result.errors, [])
  172. finally:
  173. warnings.filters[:] = originalWarnings
  174. def test_multipleFlushes(self):
  175. """
  176. Any warnings emitted after a call to C{flushWarnings} can be flushed by
  177. another call to C{flushWarnings}.
  178. """
  179. warnings.warn("first message")
  180. self.assertEqual(len(self.flushWarnings()), 1)
  181. warnings.warn("second message")
  182. self.assertEqual(len(self.flushWarnings()), 1)
  183. def test_filterOnOffendingFunction(self):
  184. """
  185. The list returned by C{flushWarnings} includes only those
  186. warnings which refer to the source of the function passed as the value
  187. for C{offendingFunction}, if a value is passed for that parameter.
  188. """
  189. firstMessage = "first warning text"
  190. firstCategory = UserWarning
  191. def one():
  192. warnings.warn(firstMessage, firstCategory, stacklevel=1)
  193. secondMessage = "some text"
  194. secondCategory = RuntimeWarning
  195. def two():
  196. warnings.warn(secondMessage, secondCategory, stacklevel=1)
  197. one()
  198. two()
  199. self.assertDictSubsets(
  200. self.flushWarnings(offendingFunctions=[one]),
  201. [{'category': firstCategory, 'message': firstMessage}])
  202. self.assertDictSubsets(
  203. self.flushWarnings(offendingFunctions=[two]),
  204. [{'category': secondCategory, 'message': secondMessage}])
  205. def test_functionBoundaries(self):
  206. """
  207. Verify that warnings emitted at the very edges of a function are still
  208. determined to be emitted from that function.
  209. """
  210. def warner():
  211. warnings.warn("first line warning")
  212. warnings.warn("internal line warning")
  213. warnings.warn("last line warning")
  214. warner()
  215. self.assertEqual(
  216. len(self.flushWarnings(offendingFunctions=[warner])), 3)
  217. def test_invalidFilter(self):
  218. """
  219. If an object which is neither a function nor a method is included in the
  220. C{offendingFunctions} list, C{flushWarnings} raises L{ValueError}. Such
  221. a call flushes no warnings.
  222. """
  223. warnings.warn("oh no")
  224. self.assertRaises(ValueError, self.flushWarnings, [None])
  225. self.assertEqual(len(self.flushWarnings()), 1)
  226. def test_missingSource(self):
  227. """
  228. Warnings emitted by a function the source code of which is not
  229. available can still be flushed.
  230. """
  231. package = FilePath(self.mktemp().encode('utf-8')).child(b'twisted_private_helper')
  232. package.makedirs()
  233. package.child(b'__init__.py').setContent(b'')
  234. package.child(b'missingsourcefile.py').setContent(b'''
  235. import warnings
  236. def foo():
  237. warnings.warn("oh no")
  238. ''')
  239. pathEntry = package.parent().path.decode('utf-8')
  240. sys.path.insert(0, pathEntry)
  241. self.addCleanup(sys.path.remove, pathEntry)
  242. from twisted_private_helper import missingsourcefile
  243. self.addCleanup(sys.modules.pop, 'twisted_private_helper')
  244. self.addCleanup(sys.modules.pop, missingsourcefile.__name__)
  245. package.child(b'missingsourcefile.py').remove()
  246. missingsourcefile.foo()
  247. self.assertEqual(len(self.flushWarnings([missingsourcefile.foo])), 1)
  248. def test_renamedSource(self):
  249. """
  250. Warnings emitted by a function defined in a file which has been renamed
  251. since it was initially compiled can still be flushed.
  252. This is testing the code which specifically supports working around the
  253. unfortunate behavior of CPython to write a .py source file name into
  254. the .pyc files it generates and then trust that it is correct in
  255. various places. If source files are renamed, .pyc files may not be
  256. regenerated, but they will contain incorrect filenames.
  257. """
  258. package = FilePath(self.mktemp().encode('utf-8')).child(b'twisted_private_helper')
  259. package.makedirs()
  260. package.child(b'__init__.py').setContent(b'')
  261. package.child(b'module.py').setContent(b'''
  262. import warnings
  263. def foo():
  264. warnings.warn("oh no")
  265. ''')
  266. pathEntry = package.parent().path.decode('utf-8')
  267. sys.path.insert(0, pathEntry)
  268. self.addCleanup(sys.path.remove, pathEntry)
  269. # Import it to cause pycs to be generated
  270. from twisted_private_helper import module
  271. # Clean up the state resulting from that import; we're not going to use
  272. # this module, so it should go away.
  273. del sys.modules['twisted_private_helper']
  274. del sys.modules[module.__name__]
  275. # Some Python versions have extra state related to the just
  276. # imported/renamed package. Clean it up too. See also
  277. # http://bugs.python.org/issue15912
  278. try:
  279. from importlib import invalidate_caches
  280. except ImportError:
  281. pass
  282. else:
  283. invalidate_caches()
  284. # Rename the source directory
  285. package.moveTo(package.sibling(b'twisted_renamed_helper'))
  286. # Import the newly renamed version
  287. from twisted_renamed_helper import module
  288. self.addCleanup(sys.modules.pop, 'twisted_renamed_helper')
  289. self.addCleanup(sys.modules.pop, module.__name__)
  290. # Generate the warning
  291. module.foo()
  292. # Flush it
  293. self.assertEqual(len(self.flushWarnings([module.foo])), 1)
  294. class FakeWarning(Warning):
  295. pass
  296. class CollectWarningsTests(SynchronousTestCase):
  297. """
  298. Tests for L{_collectWarnings}.
  299. """
  300. def test_callsObserver(self):
  301. """
  302. L{_collectWarnings} calls the observer with each emitted warning.
  303. """
  304. firstMessage = "dummy calls observer warning"
  305. secondMessage = firstMessage[::-1]
  306. thirdMessage = Warning(1, 2, 3)
  307. events = []
  308. def f():
  309. events.append('call')
  310. warnings.warn(firstMessage)
  311. warnings.warn(secondMessage)
  312. warnings.warn(thirdMessage)
  313. events.append('returning')
  314. _collectWarnings(events.append, f)
  315. self.assertEqual(events[0], 'call')
  316. self.assertEqual(events[1].message, firstMessage)
  317. self.assertEqual(events[2].message, secondMessage)
  318. self.assertEqual(events[3].message, str(thirdMessage))
  319. self.assertEqual(events[4], 'returning')
  320. self.assertEqual(len(events), 5)
  321. def test_suppresses(self):
  322. """
  323. Any warnings emitted by a call to a function passed to
  324. L{_collectWarnings} are not actually emitted to the warning system.
  325. """
  326. output = StringIO()
  327. self.patch(sys, 'stdout', output)
  328. _collectWarnings(lambda x: None, warnings.warn, "text")
  329. self.assertEqual(output.getvalue(), "")
  330. def test_callsFunction(self):
  331. """
  332. L{_collectWarnings} returns the result of calling the callable passed to
  333. it with the parameters given.
  334. """
  335. arguments = []
  336. value = object()
  337. def f(*args, **kwargs):
  338. arguments.append((args, kwargs))
  339. return value
  340. result = _collectWarnings(lambda x: None, f, 1, 'a', b=2, c='d')
  341. self.assertEqual(arguments, [((1, 'a'), {'b': 2, 'c': 'd'})])
  342. self.assertIdentical(result, value)
  343. def test_duplicateWarningCollected(self):
  344. """
  345. Subsequent emissions of a warning from a particular source site can be
  346. collected by L{_collectWarnings}. In particular, the per-module
  347. emitted-warning cache should be bypassed (I{__warningregistry__}).
  348. """
  349. # Make sure the worst case is tested: if __warningregistry__ isn't in a
  350. # module's globals, then the warning system will add it and start using
  351. # it to avoid emitting duplicate warnings. Delete __warningregistry__
  352. # to ensure that even modules which are first imported as a test is
  353. # running still interact properly with the warning system.
  354. global __warningregistry__
  355. del __warningregistry__
  356. def f():
  357. warnings.warn("foo")
  358. warnings.simplefilter('default')
  359. f()
  360. events = []
  361. _collectWarnings(events.append, f)
  362. self.assertEqual(len(events), 1)
  363. self.assertEqual(events[0].message, "foo")
  364. self.assertEqual(len(self.flushWarnings()), 1)
  365. def test_immutableObject(self):
  366. """
  367. L{_collectWarnings}'s behavior is not altered by the presence of an
  368. object which cannot have attributes set on it as a value in
  369. C{sys.modules}.
  370. """
  371. key = object()
  372. sys.modules[key] = key
  373. self.addCleanup(sys.modules.pop, key)
  374. self.test_duplicateWarningCollected()
  375. def test_setWarningRegistryChangeWhileIterating(self):
  376. """
  377. If the dictionary passed to L{_setWarningRegistryToNone} changes size
  378. partway through the process, C{_setWarningRegistryToNone} continues to
  379. set C{__warningregistry__} to L{None} on the rest of the values anyway.
  380. This might be caused by C{sys.modules} containing something that's not
  381. really a module and imports things on setattr. py.test does this, as
  382. does L{twisted.python.deprecate.deprecatedModuleAttribute}.
  383. """
  384. d = {}
  385. class A(object):
  386. def __init__(self, key):
  387. self.__dict__['_key'] = key
  388. def __setattr__(self, value, item):
  389. d[self._key] = None
  390. key1 = object()
  391. key2 = object()
  392. d[key1] = A(key2)
  393. key3 = object()
  394. key4 = object()
  395. d[key3] = A(key4)
  396. _setWarningRegistryToNone(d)
  397. # If both key2 and key4 were added, then both A instanced were
  398. # processed.
  399. self.assertEqual(set([key1, key2, key3, key4]), set(d.keys()))