You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_log.py 35KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  1. # Copyright (c) Twisted Matrix Laboratories.
  2. # See LICENSE for details.
  3. """
  4. Tests for L{twisted.python.log}.
  5. """
  6. from __future__ import division, absolute_import, print_function
  7. from twisted.python.compat import _PY3, NativeStringIO as StringIO
  8. import os
  9. import sys
  10. import time
  11. import logging
  12. import warnings
  13. import calendar
  14. from io import IOBase
  15. from imp import reload
  16. from twisted.trial import unittest
  17. from twisted.python import log, failure
  18. from twisted.logger.test.test_stdlib import handlerAndBytesIO
  19. from twisted.python.log import LogPublisher
  20. from twisted.logger import (
  21. LoggingFile, LogLevel as NewLogLevel, LogBeginner,
  22. LogPublisher as NewLogPublisher
  23. )
  24. class FakeWarning(Warning):
  25. """
  26. A unique L{Warning} subclass used by tests for interactions of
  27. L{twisted.python.log} with the L{warnings} module.
  28. """
  29. class TextFromEventDictTests(unittest.SynchronousTestCase):
  30. """
  31. Tests for L{textFromEventDict}.
  32. """
  33. def test_message(self):
  34. """
  35. The C{"message"} value, when specified, is concatenated to generate the
  36. message.
  37. """
  38. eventDict = dict(message=("a", "b", "c"))
  39. text = log.textFromEventDict(eventDict)
  40. self.assertEqual(text, "a b c")
  41. def test_format(self):
  42. """
  43. The C{"format"} value, when specified, is used to format the message.
  44. """
  45. eventDict = dict(
  46. message=(), isError=0, format="Hello, %(foo)s!", foo="dude"
  47. )
  48. text = log.textFromEventDict(eventDict)
  49. self.assertEqual(text, "Hello, dude!")
  50. def test_noMessageNoFormat(self):
  51. """
  52. If C{"format"} is unspecified and C{"message"} is empty, return
  53. L{None}.
  54. """
  55. eventDict = dict(message=(), isError=0)
  56. text = log.textFromEventDict(eventDict)
  57. self.assertIsNone(text)
  58. def test_whySpecified(self):
  59. """
  60. The C{"why"} value, when specified, is first part of message.
  61. """
  62. try:
  63. raise RuntimeError()
  64. except:
  65. eventDict = dict(
  66. message=(), isError=1, failure=failure.Failure(), why="foo"
  67. )
  68. text = log.textFromEventDict(eventDict)
  69. self.assertTrue(text.startswith("foo\n"))
  70. def test_whyDefault(self):
  71. """
  72. The C{"why"} value, when unspecified, defaults to C{"Unhandled Error"}.
  73. """
  74. try:
  75. raise RuntimeError()
  76. except:
  77. eventDict = dict(message=(), isError=1, failure=failure.Failure())
  78. text = log.textFromEventDict(eventDict)
  79. self.assertTrue(text.startswith("Unhandled Error\n"))
  80. def test_noTracebackForYou(self):
  81. """
  82. If unable to obtain a traceback due to an exception, catch it and note
  83. the error.
  84. """
  85. # Invalid failure object doesn't implement .getTraceback()
  86. eventDict = dict(message=(), isError=1, failure=object())
  87. text = log.textFromEventDict(eventDict)
  88. self.assertIn("\n(unable to obtain traceback)", text)
  89. class LogTests(unittest.SynchronousTestCase):
  90. def setUp(self):
  91. self.catcher = []
  92. self.observer = self.catcher.append
  93. log.addObserver(self.observer)
  94. self.addCleanup(log.removeObserver, self.observer)
  95. def testObservation(self):
  96. catcher = self.catcher
  97. log.msg("test", testShouldCatch=True)
  98. i = catcher.pop()
  99. self.assertEqual(i["message"][0], "test")
  100. self.assertTrue(i["testShouldCatch"])
  101. self.assertIn("time", i)
  102. self.assertEqual(len(catcher), 0)
  103. def testContext(self):
  104. catcher = self.catcher
  105. log.callWithContext({"subsystem": "not the default",
  106. "subsubsystem": "a",
  107. "other": "c"},
  108. log.callWithContext,
  109. {"subsubsystem": "b"}, log.msg, "foo", other="d")
  110. i = catcher.pop()
  111. self.assertEqual(i['subsubsystem'], 'b')
  112. self.assertEqual(i['subsystem'], 'not the default')
  113. self.assertEqual(i['other'], 'd')
  114. self.assertEqual(i['message'][0], 'foo')
  115. def testErrors(self):
  116. for e, ig in [("hello world", "hello world"),
  117. (KeyError(), KeyError),
  118. (failure.Failure(RuntimeError()), RuntimeError)]:
  119. log.err(e)
  120. i = self.catcher.pop()
  121. self.assertEqual(i['isError'], 1)
  122. self.flushLoggedErrors(ig)
  123. def testErrorsWithWhy(self):
  124. for e, ig in [("hello world", "hello world"),
  125. (KeyError(), KeyError),
  126. (failure.Failure(RuntimeError()), RuntimeError)]:
  127. log.err(e, 'foobar')
  128. i = self.catcher.pop()
  129. self.assertEqual(i['isError'], 1)
  130. self.assertEqual(i['why'], 'foobar')
  131. self.flushLoggedErrors(ig)
  132. def test_erroneousErrors(self):
  133. """
  134. Exceptions raised by log observers are logged but the observer which
  135. raised the exception remains registered with the publisher. These
  136. exceptions do not prevent the event from being sent to other observers
  137. registered with the publisher.
  138. """
  139. L1 = []
  140. L2 = []
  141. def broken(event):
  142. 1 // 0
  143. for observer in [L1.append, broken, L2.append]:
  144. log.addObserver(observer)
  145. self.addCleanup(log.removeObserver, observer)
  146. for i in range(3):
  147. # Reset the lists for simpler comparison.
  148. L1[:] = []
  149. L2[:] = []
  150. # Send out the event which will break one of the observers.
  151. log.msg("Howdy, y'all.", log_trace=[])
  152. # The broken observer should have caused this to be logged.
  153. excs = self.flushLoggedErrors(ZeroDivisionError)
  154. del self.catcher[:]
  155. self.assertEqual(len(excs), 1)
  156. # Both other observers should have seen the message.
  157. self.assertEqual(len(L1), 2)
  158. self.assertEqual(len(L2), 2)
  159. # The first event is delivered to all observers; then, errors
  160. # are delivered.
  161. self.assertEqual(L1[0]['message'], ("Howdy, y'all.",))
  162. self.assertEqual(L2[0]['message'], ("Howdy, y'all.",))
  163. def test_showwarning(self):
  164. """
  165. L{twisted.python.log.showwarning} emits the warning as a message
  166. to the Twisted logging system.
  167. """
  168. publisher = log.LogPublisher()
  169. publisher.addObserver(self.observer)
  170. publisher.showwarning(
  171. FakeWarning("unique warning message"), FakeWarning,
  172. "warning-filename.py", 27)
  173. event = self.catcher.pop()
  174. self.assertEqual(
  175. event['format'] % event,
  176. 'warning-filename.py:27: twisted.test.test_log.FakeWarning: '
  177. 'unique warning message')
  178. self.assertEqual(self.catcher, [])
  179. # Python 2.6 requires that any function used to override the
  180. # warnings.showwarning API accept a "line" parameter or a
  181. # deprecation warning is emitted.
  182. publisher.showwarning(
  183. FakeWarning("unique warning message"), FakeWarning,
  184. "warning-filename.py", 27, line=object())
  185. event = self.catcher.pop()
  186. self.assertEqual(
  187. event['format'] % event,
  188. 'warning-filename.py:27: twisted.test.test_log.FakeWarning: '
  189. 'unique warning message')
  190. self.assertEqual(self.catcher, [])
  191. def test_warningToFile(self):
  192. """
  193. L{twisted.python.log.showwarning} passes warnings with an explicit file
  194. target on to the underlying Python warning system.
  195. """
  196. message = "another unique message"
  197. category = FakeWarning
  198. filename = "warning-filename.py"
  199. lineno = 31
  200. output = StringIO()
  201. log.showwarning(message, category, filename, lineno, file=output)
  202. self.assertEqual(
  203. output.getvalue(),
  204. warnings.formatwarning(message, category, filename, lineno))
  205. # In Python 2.6 and higher, warnings.showwarning accepts
  206. # a "line" argument which gives the source line the warning
  207. # message is to include.
  208. line = "hello world"
  209. output = StringIO()
  210. log.showwarning(message, category, filename, lineno, file=output,
  211. line=line)
  212. self.assertEqual(
  213. output.getvalue(),
  214. warnings.formatwarning(message, category, filename, lineno,
  215. line))
  216. def test_publisherReportsBrokenObserversPrivately(self):
  217. """
  218. Log publisher does not use the global L{log.err} when reporting broken
  219. observers.
  220. """
  221. errors = []
  222. def logError(eventDict):
  223. if eventDict.get("isError"):
  224. errors.append(eventDict["failure"].value)
  225. def fail(eventDict):
  226. raise RuntimeError("test_publisherLocalyReportsBrokenObservers")
  227. publisher = log.LogPublisher()
  228. publisher.addObserver(logError)
  229. publisher.addObserver(fail)
  230. publisher.msg("Hello!")
  231. self.assertEqual(set(publisher.observers), set([logError, fail]))
  232. self.assertEqual(len(errors), 1)
  233. self.assertIsInstance(errors[0], RuntimeError)
  234. class FakeFile(list):
  235. def write(self, bytes):
  236. self.append(bytes)
  237. def flush(self):
  238. pass
  239. IOBase.register(FakeFile)
  240. class EvilStr:
  241. def __str__(self):
  242. 1 // 0
  243. class EvilRepr:
  244. def __str__(self):
  245. return "Happy Evil Repr"
  246. def __repr__(self):
  247. 1 // 0
  248. class EvilReprStr(EvilStr, EvilRepr):
  249. pass
  250. class LogPublisherTestCaseMixin:
  251. def setUp(self):
  252. """
  253. Add a log observer which records log events in C{self.out}. Also,
  254. make sure the default string encoding is ASCII so that
  255. L{testSingleUnicode} can test the behavior of logging unencodable
  256. unicode messages.
  257. """
  258. self.out = FakeFile()
  259. self.lp = log.LogPublisher()
  260. self.flo = log.FileLogObserver(self.out)
  261. self.lp.addObserver(self.flo.emit)
  262. try:
  263. str(u'\N{VULGAR FRACTION ONE HALF}')
  264. except UnicodeEncodeError:
  265. # This is the behavior we want - don't change anything.
  266. self._origEncoding = None
  267. else:
  268. if _PY3:
  269. self._origEncoding = None
  270. return
  271. reload(sys)
  272. self._origEncoding = sys.getdefaultencoding()
  273. sys.setdefaultencoding('ascii')
  274. def tearDown(self):
  275. """
  276. Verify that everything written to the fake file C{self.out} was a
  277. C{str}. Also, restore the default string encoding to its previous
  278. setting, if it was modified by L{setUp}.
  279. """
  280. for chunk in self.out:
  281. self.assertIsInstance(chunk, str,
  282. "%r was not a string" % (chunk,))
  283. if self._origEncoding is not None:
  284. sys.setdefaultencoding(self._origEncoding)
  285. del sys.setdefaultencoding
  286. class LogPublisherTests(LogPublisherTestCaseMixin,
  287. unittest.SynchronousTestCase):
  288. def testSingleString(self):
  289. self.lp.msg("Hello, world.")
  290. self.assertEqual(len(self.out), 1)
  291. def testMultipleString(self):
  292. # Test some stupid behavior that will be deprecated real soon.
  293. # If you are reading this and trying to learn how the logging
  294. # system works, *do not use this feature*.
  295. self.lp.msg("Hello, ", "world.")
  296. self.assertEqual(len(self.out), 1)
  297. def test_singleUnicode(self):
  298. """
  299. L{log.LogPublisher.msg} does not accept non-ASCII Unicode on Python 2,
  300. logging an error instead.
  301. On Python 3, where Unicode is default message type, the message is
  302. logged normally.
  303. """
  304. message = u"Hello, \N{VULGAR FRACTION ONE HALF} world."
  305. self.lp.msg(message)
  306. self.assertEqual(len(self.out), 1)
  307. if _PY3:
  308. self.assertIn(message, self.out[0])
  309. else:
  310. self.assertIn('with str error', self.out[0])
  311. self.assertIn('UnicodeEncodeError', self.out[0])
  312. class FileObserverTests(LogPublisherTestCaseMixin,
  313. unittest.SynchronousTestCase):
  314. """
  315. Tests for L{log.FileObserver}.
  316. """
  317. ERROR_INVALID_FORMAT = 'Invalid format string'
  318. ERROR_UNFORMATTABLE_OBJECT = 'UNFORMATTABLE OBJECT'
  319. ERROR_FORMAT = (
  320. 'Invalid format string or unformattable object in log message'
  321. )
  322. ERROR_PATHOLOGICAL = 'PATHOLOGICAL ERROR'
  323. ERROR_NO_FORMAT = 'Unable to format event'
  324. ERROR_UNFORMATTABLE_SYSTEM = '[UNFORMATTABLE]'
  325. ERROR_MESSAGE_LOST = 'MESSAGE LOST: unformattable object logged'
  326. def _getTimezoneOffsetTest(self, tzname, daylightOffset, standardOffset):
  327. """
  328. Verify that L{getTimezoneOffset} produces the expected offset for a
  329. certain timezone both when daylight saving time is in effect and when
  330. it is not.
  331. @param tzname: The name of a timezone to exercise.
  332. @type tzname: L{bytes}
  333. @param daylightOffset: The number of seconds west of UTC the timezone
  334. should be when daylight saving time is in effect.
  335. @type daylightOffset: L{int}
  336. @param standardOffset: The number of seconds west of UTC the timezone
  337. should be when daylight saving time is not in effect.
  338. @type standardOffset: L{int}
  339. """
  340. if getattr(time, 'tzset', None) is None:
  341. raise unittest.SkipTest(
  342. "Platform cannot change timezone, cannot verify correct "
  343. "offsets in well-known timezones.")
  344. originalTimezone = os.environ.get('TZ', None)
  345. try:
  346. os.environ['TZ'] = tzname
  347. time.tzset()
  348. # The behavior of mktime depends on the current timezone setting.
  349. # So only do this after changing the timezone.
  350. # Compute a POSIX timestamp for a certain date and time that is
  351. # known to occur at a time when daylight saving time is in effect.
  352. localDaylightTuple = (2006, 6, 30, 0, 0, 0, 4, 181, 1)
  353. daylight = time.mktime(localDaylightTuple)
  354. # Compute a POSIX timestamp for a certain date and time that is
  355. # known to occur at a time when daylight saving time is not in
  356. # effect.
  357. localStandardTuple = (2007, 1, 31, 0, 0, 0, 2, 31, 0)
  358. standard = time.mktime(localStandardTuple)
  359. self.assertEqual(
  360. (self.flo.getTimezoneOffset(daylight),
  361. self.flo.getTimezoneOffset(standard)),
  362. (daylightOffset, standardOffset))
  363. finally:
  364. if originalTimezone is None:
  365. del os.environ['TZ']
  366. else:
  367. os.environ['TZ'] = originalTimezone
  368. time.tzset()
  369. def test_getTimezoneOffsetWestOfUTC(self):
  370. """
  371. Attempt to verify that L{FileLogObserver.getTimezoneOffset} returns
  372. correct values for the current C{TZ} environment setting for at least
  373. some cases. This test method exercises a timezone that is west of UTC
  374. (and should produce positive results).
  375. """
  376. self._getTimezoneOffsetTest("America/New_York", 14400, 18000)
  377. def test_getTimezoneOffsetEastOfUTC(self):
  378. """
  379. Attempt to verify that L{FileLogObserver.getTimezoneOffset} returns
  380. correct values for the current C{TZ} environment setting for at least
  381. some cases. This test method exercises a timezone that is east of UTC
  382. (and should produce negative results).
  383. """
  384. self._getTimezoneOffsetTest("Europe/Berlin", -7200, -3600)
  385. def test_getTimezoneOffsetWithoutDaylightSavingTime(self):
  386. """
  387. Attempt to verify that L{FileLogObserver.getTimezoneOffset} returns
  388. correct values for the current C{TZ} environment setting for at least
  389. some cases. This test method exercises a timezone that does not use
  390. daylight saving time at all (so both summer and winter time test values
  391. should have the same offset).
  392. """
  393. # Test a timezone that doesn't have DST. mktime() implementations
  394. # available for testing seem happy to produce results for this even
  395. # though it's not entirely valid.
  396. self._getTimezoneOffsetTest("Africa/Johannesburg", -7200, -7200)
  397. def test_timeFormatting(self):
  398. """
  399. Test the method of L{FileLogObserver} which turns a timestamp into a
  400. human-readable string.
  401. """
  402. when = calendar.timegm((2001, 2, 3, 4, 5, 6, 7, 8, 0))
  403. # Pretend to be in US/Eastern for a moment
  404. self.flo.getTimezoneOffset = lambda when: 18000
  405. self.assertEqual(self.flo.formatTime(when), '2001-02-02 23:05:06-0500')
  406. # Okay now we're in Eastern Europe somewhere
  407. self.flo.getTimezoneOffset = lambda when: -3600
  408. self.assertEqual(self.flo.formatTime(when), '2001-02-03 05:05:06+0100')
  409. # And off in the Pacific or someplace like that
  410. self.flo.getTimezoneOffset = lambda when: -39600
  411. self.assertEqual(self.flo.formatTime(when), '2001-02-03 15:05:06+1100')
  412. # One of those weird places with a half-hour offset timezone
  413. self.flo.getTimezoneOffset = lambda when: 5400
  414. self.assertEqual(self.flo.formatTime(when), '2001-02-03 02:35:06-0130')
  415. # Half-hour offset in the other direction
  416. self.flo.getTimezoneOffset = lambda when: -5400
  417. self.assertEqual(self.flo.formatTime(when), '2001-02-03 05:35:06+0130')
  418. # Test an offset which is between 0 and 60 minutes to make sure the
  419. # sign comes out properly in that case.
  420. self.flo.getTimezoneOffset = lambda when: 1800
  421. self.assertEqual(self.flo.formatTime(when), '2001-02-03 03:35:06-0030')
  422. # Test an offset between 0 and 60 minutes in the other direction.
  423. self.flo.getTimezoneOffset = lambda when: -1800
  424. self.assertEqual(self.flo.formatTime(when), '2001-02-03 04:35:06+0030')
  425. # If a strftime-format string is present on the logger, it should
  426. # use that instead. Note we don't assert anything about day, hour
  427. # or minute because we cannot easily control what time.strftime()
  428. # thinks the local timezone is.
  429. self.flo.timeFormat = '%Y %m'
  430. self.assertEqual(self.flo.formatTime(when), '2001 02')
  431. def test_microsecondTimestampFormatting(self):
  432. """
  433. L{FileLogObserver.formatTime} supports a value of C{timeFormat} which
  434. includes C{"%f"}, a L{datetime}-only format specifier for microseconds.
  435. """
  436. self.flo.timeFormat = '%f'
  437. self.assertEqual("600000", self.flo.formatTime(112345.6))
  438. def test_loggingAnObjectWithBroken__str__(self):
  439. # HELLO, MCFLY
  440. self.lp.msg(EvilStr())
  441. self.assertEqual(len(self.out), 1)
  442. # Logging system shouldn't need to crap itself for this trivial case
  443. self.assertNotIn(self.ERROR_UNFORMATTABLE_OBJECT, self.out[0])
  444. def test_formattingAnObjectWithBroken__str__(self):
  445. self.lp.msg(format='%(blat)s', blat=EvilStr())
  446. self.assertEqual(len(self.out), 1)
  447. self.assertIn(self.ERROR_INVALID_FORMAT, self.out[0])
  448. def test_brokenSystem__str__(self):
  449. self.lp.msg('huh', system=EvilStr())
  450. self.assertEqual(len(self.out), 1)
  451. self.assertIn(self.ERROR_FORMAT, self.out[0])
  452. def test_formattingAnObjectWithBroken__repr__Indirect(self):
  453. self.lp.msg(format='%(blat)s', blat=[EvilRepr()])
  454. self.assertEqual(len(self.out), 1)
  455. self.assertIn(self.ERROR_UNFORMATTABLE_OBJECT, self.out[0])
  456. def test_systemWithBroker__repr__Indirect(self):
  457. self.lp.msg('huh', system=[EvilRepr()])
  458. self.assertEqual(len(self.out), 1)
  459. self.assertIn(self.ERROR_UNFORMATTABLE_OBJECT, self.out[0])
  460. def test_simpleBrokenFormat(self):
  461. self.lp.msg(format='hooj %s %s', blat=1)
  462. self.assertEqual(len(self.out), 1)
  463. self.assertIn(self.ERROR_INVALID_FORMAT, self.out[0])
  464. def test_ridiculousFormat(self):
  465. self.lp.msg(format=42, blat=1)
  466. self.assertEqual(len(self.out), 1)
  467. self.assertIn(self.ERROR_INVALID_FORMAT, self.out[0])
  468. def test_evilFormat__repr__And__str__(self):
  469. self.lp.msg(format=EvilReprStr(), blat=1)
  470. self.assertEqual(len(self.out), 1)
  471. self.assertIn(self.ERROR_PATHOLOGICAL, self.out[0])
  472. def test_strangeEventDict(self):
  473. """
  474. This kind of eventDict used to fail silently, so test it does.
  475. """
  476. self.lp.msg(message='', isError=False)
  477. self.assertEqual(len(self.out), 0)
  478. def _startLoggingCleanup(self):
  479. """
  480. Cleanup after a startLogging() call that mutates the hell out of some
  481. global state.
  482. """
  483. self.addCleanup(log.theLogPublisher._stopLogging)
  484. self.addCleanup(setattr, sys, 'stdout', sys.stdout)
  485. self.addCleanup(setattr, sys, 'stderr', sys.stderr)
  486. def test_printToStderrSetsIsError(self):
  487. """
  488. startLogging()'s overridden sys.stderr should consider everything
  489. written to it an error.
  490. """
  491. self._startLoggingCleanup()
  492. fakeFile = StringIO()
  493. log.startLogging(fakeFile)
  494. def observe(event):
  495. observed.append(event)
  496. observed = []
  497. log.addObserver(observe)
  498. print("Hello, world.", file=sys.stderr)
  499. self.assertEqual(observed[0]["isError"], 1)
  500. def test_startLogging(self):
  501. """
  502. startLogging() installs FileLogObserver and overrides sys.stdout and
  503. sys.stderr.
  504. """
  505. origStdout, origStderr = sys.stdout, sys.stderr
  506. self._startLoggingCleanup()
  507. # When done with test, reset stdout and stderr to current values:
  508. fakeFile = StringIO()
  509. observer = log.startLogging(fakeFile)
  510. self.addCleanup(observer.stop)
  511. log.msg("Hello!")
  512. self.assertIn("Hello!", fakeFile.getvalue())
  513. self.assertIsInstance(sys.stdout, LoggingFile)
  514. self.assertEqual(sys.stdout.level, NewLogLevel.info)
  515. encoding = getattr(origStdout, "encoding", None)
  516. if not encoding:
  517. encoding = sys.getdefaultencoding()
  518. self.assertEqual(sys.stdout.encoding.upper(), encoding.upper())
  519. self.assertIsInstance(sys.stderr, LoggingFile)
  520. self.assertEqual(sys.stderr.level, NewLogLevel.error)
  521. encoding = getattr(origStderr, "encoding", None)
  522. if not encoding:
  523. encoding = sys.getdefaultencoding()
  524. self.assertEqual(sys.stderr.encoding.upper(), encoding.upper())
  525. def test_startLoggingTwice(self):
  526. """
  527. There are some obscure error conditions that can occur when logging is
  528. started twice. See http://twistedmatrix.com/trac/ticket/3289 for more
  529. information.
  530. """
  531. self._startLoggingCleanup()
  532. # The bug is particular to the way that the t.p.log 'global' function
  533. # handle stdout. If we use our own stream, the error doesn't occur. If
  534. # we use our own LogPublisher, the error doesn't occur.
  535. sys.stdout = StringIO()
  536. def showError(eventDict):
  537. if eventDict['isError']:
  538. sys.__stdout__.write(eventDict['failure'].getTraceback())
  539. log.addObserver(showError)
  540. self.addCleanup(log.removeObserver, showError)
  541. observer = log.startLogging(sys.stdout)
  542. self.addCleanup(observer.stop)
  543. # At this point, we expect that sys.stdout is a StdioOnnaStick object.
  544. self.assertIsInstance(sys.stdout, LoggingFile)
  545. fakeStdout = sys.stdout
  546. observer = log.startLogging(sys.stdout)
  547. self.assertIs(sys.stdout, fakeStdout)
  548. def test_startLoggingOverridesWarning(self):
  549. """
  550. startLogging() overrides global C{warnings.showwarning} such that
  551. warnings go to Twisted log observers.
  552. """
  553. self._startLoggingCleanup()
  554. newPublisher = NewLogPublisher()
  555. class SysModule(object):
  556. stdout = object()
  557. stderr = object()
  558. tempLogPublisher = LogPublisher(
  559. newPublisher, newPublisher,
  560. logBeginner=LogBeginner(newPublisher, StringIO(), SysModule,
  561. warnings)
  562. )
  563. # Trial reports warnings in two ways. First, it intercepts the global
  564. # 'showwarning' function *itself*, after starting logging (by way of
  565. # the '_collectWarnings' function which collects all warnings as a
  566. # around the test's 'run' method). Second, it has a log observer which
  567. # immediately reports warnings when they're propagated into the log
  568. # system (which, in normal operation, happens only at the end of the
  569. # test case). In order to avoid printing a spurious warning in this
  570. # test, we first replace the global log publisher's 'showwarning' in
  571. # the module with our own.
  572. self.patch(log, "theLogPublisher", tempLogPublisher)
  573. # And, one last thing, pretend we're starting from a fresh import, or
  574. # warnings.warn won't be patched at all.
  575. log._oldshowwarning = None
  576. # Global mutable state is bad, kids. Stay in school.
  577. fakeFile = StringIO()
  578. # We didn't previously save log messages, so let's make sure we don't
  579. # save them any more.
  580. evt = {"pre-start": "event"}
  581. received = []
  582. def preStartObserver(x):
  583. if 'pre-start' in x.keys():
  584. received.append(x)
  585. newPublisher(evt)
  586. newPublisher.addObserver(preStartObserver)
  587. log.startLogging(fakeFile, setStdout=False)
  588. self.addCleanup(tempLogPublisher._stopLogging)
  589. self.assertEqual(received, [])
  590. warnings.warn("hello!")
  591. output = fakeFile.getvalue()
  592. self.assertIn("UserWarning: hello!", output)
  593. def test_emitPrefix(self):
  594. """
  595. FileLogObserver.emit() will add a timestamp and system prefix to its
  596. file output.
  597. """
  598. output = StringIO()
  599. flo = log.FileLogObserver(output)
  600. events = []
  601. def observer(event):
  602. # Capture the event for reference and pass it along to flo
  603. events.append(event)
  604. flo.emit(event)
  605. publisher = log.LogPublisher()
  606. publisher.addObserver(observer)
  607. publisher.msg("Hello!")
  608. self.assertEqual(len(events), 1)
  609. event = events[0]
  610. result = output.getvalue()
  611. prefix = "{time} [{system}] ".format(
  612. time=flo.formatTime(event["time"]), system=event["system"],
  613. )
  614. self.assertTrue(
  615. result.startswith(prefix),
  616. "{0!r} does not start with {1!r}".format(result, prefix)
  617. )
  618. def test_emitNewline(self):
  619. """
  620. FileLogObserver.emit() will append a newline to its file output.
  621. """
  622. output = StringIO()
  623. flo = log.FileLogObserver(output)
  624. publisher = log.LogPublisher()
  625. publisher.addObserver(flo.emit)
  626. publisher.msg("Hello!")
  627. result = output.getvalue()
  628. suffix = "Hello!\n"
  629. self.assertTrue(
  630. result.endswith(suffix),
  631. "{0!r} does not end with {1!r}".format(result, suffix)
  632. )
  633. class PythonLoggingObserverTests(unittest.SynchronousTestCase):
  634. """
  635. Test the bridge with python logging module.
  636. """
  637. def setUp(self):
  638. rootLogger = logging.getLogger("")
  639. originalLevel = rootLogger.getEffectiveLevel()
  640. rootLogger.setLevel(logging.DEBUG)
  641. @self.addCleanup
  642. def restoreLevel():
  643. rootLogger.setLevel(originalLevel)
  644. self.hdlr, self.out = handlerAndBytesIO()
  645. rootLogger.addHandler(self.hdlr)
  646. @self.addCleanup
  647. def removeLogger():
  648. rootLogger.removeHandler(self.hdlr)
  649. self.hdlr.close()
  650. self.lp = log.LogPublisher()
  651. self.obs = log.PythonLoggingObserver()
  652. self.lp.addObserver(self.obs.emit)
  653. def test_singleString(self):
  654. """
  655. Test simple output, and default log level.
  656. """
  657. self.lp.msg("Hello, world.")
  658. self.assertIn(b"Hello, world.", self.out.getvalue())
  659. self.assertIn(b"INFO", self.out.getvalue())
  660. def test_errorString(self):
  661. """
  662. Test error output.
  663. """
  664. f = failure.Failure(ValueError("That is bad."))
  665. self.lp.msg(failure=f, isError=True)
  666. prefix = b"CRITICAL:"
  667. output = self.out.getvalue()
  668. self.assertTrue(
  669. output.startswith(prefix),
  670. "Does not start with {0!r}: {1!r}".format(prefix, output)
  671. )
  672. def test_formatString(self):
  673. """
  674. Test logging with a format.
  675. """
  676. self.lp.msg(format="%(bar)s oo %(foo)s", bar="Hello", foo="world")
  677. self.assertIn(b"Hello oo world", self.out.getvalue())
  678. def test_customLevel(self):
  679. """
  680. Test the logLevel keyword for customizing level used.
  681. """
  682. self.lp.msg("Spam egg.", logLevel=logging.ERROR)
  683. self.assertIn(b"Spam egg.", self.out.getvalue())
  684. self.assertIn(b"ERROR", self.out.getvalue())
  685. self.out.seek(0, 0)
  686. self.out.truncate()
  687. self.lp.msg("Foo bar.", logLevel=logging.WARNING)
  688. self.assertIn(b"Foo bar.", self.out.getvalue())
  689. self.assertIn(b"WARNING", self.out.getvalue())
  690. def test_strangeEventDict(self):
  691. """
  692. Verify that an event dictionary which is not an error and has an empty
  693. message isn't recorded.
  694. """
  695. self.lp.msg(message='', isError=False)
  696. self.assertEqual(self.out.getvalue(), b'')
  697. class PythonLoggingIntegrationTests(unittest.SynchronousTestCase):
  698. """
  699. Test integration of python logging bridge.
  700. """
  701. def test_startStopObserver(self):
  702. """
  703. Test that start and stop methods of the observer actually register
  704. and unregister to the log system.
  705. """
  706. oldAddObserver = log.addObserver
  707. oldRemoveObserver = log.removeObserver
  708. l = []
  709. try:
  710. log.addObserver = l.append
  711. log.removeObserver = l.remove
  712. obs = log.PythonLoggingObserver()
  713. obs.start()
  714. self.assertEqual(l[0], obs.emit)
  715. obs.stop()
  716. self.assertEqual(len(l), 0)
  717. finally:
  718. log.addObserver = oldAddObserver
  719. log.removeObserver = oldRemoveObserver
  720. def test_inheritance(self):
  721. """
  722. Test that we can inherit L{log.PythonLoggingObserver} and use super:
  723. that's basically a validation that L{log.PythonLoggingObserver} is
  724. new-style class.
  725. """
  726. class MyObserver(log.PythonLoggingObserver):
  727. def emit(self, eventDict):
  728. super(MyObserver, self).emit(eventDict)
  729. obs = MyObserver()
  730. l = []
  731. oldEmit = log.PythonLoggingObserver.emit
  732. try:
  733. log.PythonLoggingObserver.emit = l.append
  734. obs.emit('foo')
  735. self.assertEqual(len(l), 1)
  736. finally:
  737. log.PythonLoggingObserver.emit = oldEmit
  738. class DefaultObserverTests(unittest.SynchronousTestCase):
  739. """
  740. Test the default observer.
  741. """
  742. def test_failureLogger(self):
  743. """
  744. The reason argument passed to log.err() appears in the report
  745. generated by DefaultObserver.
  746. """
  747. self.catcher = []
  748. self.observer = self.catcher.append
  749. log.addObserver(self.observer)
  750. self.addCleanup(log.removeObserver, self.observer)
  751. obs = log.DefaultObserver()
  752. obs.stderr = StringIO()
  753. obs.start()
  754. self.addCleanup(obs.stop)
  755. reason = "The reason."
  756. log.err(Exception(), reason)
  757. errors = self.flushLoggedErrors()
  758. self.assertIn(reason, obs.stderr.getvalue())
  759. self.assertEqual(len(errors), 1)
  760. def test_emitEventWithBrokenRepr(self):
  761. """
  762. DefaultObserver.emit() does not raise when it observes an error event
  763. with a message that causes L{repr} to raise.
  764. """
  765. class Ouch(object):
  766. def __repr__(self):
  767. return str(1 / 0)
  768. message = ("foo", Ouch())
  769. event = dict(message=message, isError=1)
  770. observer = log.DefaultObserver()
  771. with StringIO() as output:
  772. observer.stderr = output
  773. observer.emit(event)
  774. self.assertTrue(output.getvalue().startswith("foo <Ouch instance"))
  775. class StdioOnnaStickTests(unittest.SynchronousTestCase):
  776. """
  777. StdioOnnaStick should act like the normal sys.stdout object.
  778. """
  779. def setUp(self):
  780. self.resultLogs = []
  781. log.addObserver(self.resultLogs.append)
  782. def tearDown(self):
  783. log.removeObserver(self.resultLogs.append)
  784. def getLogMessages(self):
  785. return ["".join(d['message']) for d in self.resultLogs]
  786. def test_write(self):
  787. """
  788. Writing to a StdioOnnaStick instance results in Twisted log messages.
  789. Log messages are generated every time a '\\n' is encountered.
  790. """
  791. stdio = log.StdioOnnaStick()
  792. stdio.write("Hello there\nThis is a test")
  793. self.assertEqual(self.getLogMessages(), ["Hello there"])
  794. stdio.write("!\n")
  795. self.assertEqual(self.getLogMessages(),
  796. ["Hello there", "This is a test!"])
  797. def test_metadata(self):
  798. """
  799. The log messages written by StdioOnnaStick have printed=1 keyword, and
  800. by default are not errors.
  801. """
  802. stdio = log.StdioOnnaStick()
  803. stdio.write("hello\n")
  804. self.assertFalse(self.resultLogs[0]['isError'])
  805. self.assertTrue(self.resultLogs[0]['printed'])
  806. def test_writeLines(self):
  807. """
  808. Writing lines to a StdioOnnaStick results in Twisted log messages.
  809. """
  810. stdio = log.StdioOnnaStick()
  811. stdio.writelines(["log 1", "log 2"])
  812. self.assertEqual(self.getLogMessages(), ["log 1", "log 2"])
  813. def test_print(self):
  814. """
  815. When StdioOnnaStick is set as sys.stdout, prints become log messages.
  816. """
  817. oldStdout = sys.stdout
  818. sys.stdout = log.StdioOnnaStick()
  819. self.addCleanup(setattr, sys, "stdout", oldStdout)
  820. print("This", end=" ")
  821. print("is a test")
  822. self.assertEqual(self.getLogMessages(), ["This is a test"])
  823. def test_error(self):
  824. """
  825. StdioOnnaStick created with isError=True log messages as errors.
  826. """
  827. stdio = log.StdioOnnaStick(isError=True)
  828. stdio.write("log 1\n")
  829. self.assertTrue(self.resultLogs[0]['isError'])
  830. def test_unicode(self):
  831. """
  832. StdioOnnaStick converts unicode prints to byte strings on Python 2, in
  833. order to be compatible with the normal stdout/stderr objects.
  834. On Python 3, the prints are left unmodified.
  835. """
  836. unicodeString = u"Hello, \N{VULGAR FRACTION ONE HALF} world."
  837. stdio = log.StdioOnnaStick(encoding="utf-8")
  838. self.assertEqual(stdio.encoding, "utf-8")
  839. stdio.write(unicodeString + u"\n")
  840. stdio.writelines([u"Also, " + unicodeString])
  841. oldStdout = sys.stdout
  842. sys.stdout = stdio
  843. self.addCleanup(setattr, sys, "stdout", oldStdout)
  844. # This should go to the log, utf-8 encoded too:
  845. print(unicodeString)
  846. if _PY3:
  847. self.assertEqual(self.getLogMessages(),
  848. [unicodeString,
  849. u"Also, " + unicodeString,
  850. unicodeString])
  851. else:
  852. self.assertEqual(self.getLogMessages(),
  853. [unicodeString.encode("utf-8"),
  854. (u"Also, " + unicodeString).encode("utf-8"),
  855. unicodeString.encode("utf-8")])