m2m模型翻译
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.

673 lines
30 KiB

6 months ago
  1. # Automated tests for the `coloredlogs' package.
  2. #
  3. # Author: Peter Odding <peter@peterodding.com>
  4. # Last Change: June 11, 2021
  5. # URL: https://coloredlogs.readthedocs.io
  6. """Automated tests for the `coloredlogs` package."""
  7. # Standard library modules.
  8. import contextlib
  9. import logging
  10. import logging.handlers
  11. import os
  12. import re
  13. import subprocess
  14. import sys
  15. import tempfile
  16. # External dependencies.
  17. from humanfriendly.compat import StringIO
  18. from humanfriendly.terminal import ANSI_COLOR_CODES, ANSI_CSI, ansi_style, ansi_wrap
  19. from humanfriendly.testing import PatchedAttribute, PatchedItem, TestCase, retry
  20. from humanfriendly.text import format, random_string
  21. # The module we're testing.
  22. import coloredlogs
  23. import coloredlogs.cli
  24. from coloredlogs import (
  25. CHROOT_FILES,
  26. ColoredFormatter,
  27. NameNormalizer,
  28. decrease_verbosity,
  29. find_defined_levels,
  30. find_handler,
  31. find_hostname,
  32. find_program_name,
  33. find_username,
  34. get_level,
  35. increase_verbosity,
  36. install,
  37. is_verbose,
  38. level_to_number,
  39. match_stream_handler,
  40. parse_encoded_styles,
  41. set_level,
  42. walk_propagation_tree,
  43. )
  44. from coloredlogs.demo import demonstrate_colored_logging
  45. from coloredlogs.syslog import SystemLogging, is_syslog_supported, match_syslog_handler
  46. from coloredlogs.converter import (
  47. ColoredCronMailer,
  48. EIGHT_COLOR_PALETTE,
  49. capture,
  50. convert,
  51. )
  52. # External test dependencies.
  53. from capturer import CaptureOutput
  54. from verboselogs import VerboseLogger
  55. # Compiled regular expression that matches a single line of output produced by
  56. # the default log format (does not include matching of ANSI escape sequences).
  57. PLAIN_TEXT_PATTERN = re.compile(r'''
  58. (?P<date> \d{4}-\d{2}-\d{2} )
  59. \s (?P<time> \d{2}:\d{2}:\d{2} )
  60. \s (?P<hostname> \S+ )
  61. \s (?P<logger_name> \w+ )
  62. \[ (?P<process_id> \d+ ) \]
  63. \s (?P<severity> [A-Z]+ )
  64. \s (?P<message> .* )
  65. ''', re.VERBOSE)
  66. # Compiled regular expression that matches a single line of output produced by
  67. # the default log format with milliseconds=True.
  68. PATTERN_INCLUDING_MILLISECONDS = re.compile(r'''
  69. (?P<date> \d{4}-\d{2}-\d{2} )
  70. \s (?P<time> \d{2}:\d{2}:\d{2},\d{3} )
  71. \s (?P<hostname> \S+ )
  72. \s (?P<logger_name> \w+ )
  73. \[ (?P<process_id> \d+ ) \]
  74. \s (?P<severity> [A-Z]+ )
  75. \s (?P<message> .* )
  76. ''', re.VERBOSE)
  77. def setUpModule():
  78. """Speed up the tests by disabling the demo's artificial delay."""
  79. os.environ['COLOREDLOGS_DEMO_DELAY'] = '0'
  80. coloredlogs.demo.DEMO_DELAY = 0
  81. class ColoredLogsTestCase(TestCase):
  82. """Container for the `coloredlogs` tests."""
  83. def find_system_log(self):
  84. """Find the system log file or skip the current test."""
  85. filename = ('/var/log/system.log' if sys.platform == 'darwin' else (
  86. '/var/log/syslog' if 'linux' in sys.platform else None
  87. ))
  88. if not filename:
  89. self.skipTest("Location of system log file unknown!")
  90. elif not os.path.isfile(filename):
  91. self.skipTest("System log file not found! (%s)" % filename)
  92. elif not os.access(filename, os.R_OK):
  93. self.skipTest("Insufficient permissions to read system log file! (%s)" % filename)
  94. else:
  95. return filename
  96. def test_level_to_number(self):
  97. """Make sure :func:`level_to_number()` works as intended."""
  98. # Make sure the default levels are translated as expected.
  99. assert level_to_number('debug') == logging.DEBUG
  100. assert level_to_number('info') == logging.INFO
  101. assert level_to_number('warning') == logging.WARNING
  102. assert level_to_number('error') == logging.ERROR
  103. assert level_to_number('fatal') == logging.FATAL
  104. # Make sure bogus level names don't blow up.
  105. assert level_to_number('bogus-level') == logging.INFO
  106. def test_find_hostname(self):
  107. """Make sure :func:`~find_hostname()` works correctly."""
  108. assert find_hostname()
  109. # Create a temporary file as a placeholder for e.g. /etc/debian_chroot.
  110. fd, temporary_file = tempfile.mkstemp()
  111. try:
  112. with open(temporary_file, 'w') as handle:
  113. handle.write('first line\n')
  114. handle.write('second line\n')
  115. CHROOT_FILES.insert(0, temporary_file)
  116. # Make sure the chroot file is being read.
  117. assert find_hostname() == 'first line'
  118. finally:
  119. # Clean up.
  120. CHROOT_FILES.pop(0)
  121. os.unlink(temporary_file)
  122. # Test that unreadable chroot files don't break coloredlogs.
  123. try:
  124. CHROOT_FILES.insert(0, temporary_file)
  125. # Make sure that a usable value is still produced.
  126. assert find_hostname()
  127. finally:
  128. # Clean up.
  129. CHROOT_FILES.pop(0)
  130. def test_host_name_filter(self):
  131. """Make sure :func:`install()` integrates with :class:`~coloredlogs.HostNameFilter()`."""
  132. install(fmt='%(hostname)s')
  133. with CaptureOutput() as capturer:
  134. logging.info("A truly insignificant message ..")
  135. output = capturer.get_text()
  136. assert find_hostname() in output
  137. def test_program_name_filter(self):
  138. """Make sure :func:`install()` integrates with :class:`~coloredlogs.ProgramNameFilter()`."""
  139. install(fmt='%(programname)s')
  140. with CaptureOutput() as capturer:
  141. logging.info("A truly insignificant message ..")
  142. output = capturer.get_text()
  143. assert find_program_name() in output
  144. def test_username_filter(self):
  145. """Make sure :func:`install()` integrates with :class:`~coloredlogs.UserNameFilter()`."""
  146. install(fmt='%(username)s')
  147. with CaptureOutput() as capturer:
  148. logging.info("A truly insignificant message ..")
  149. output = capturer.get_text()
  150. assert find_username() in output
  151. def test_system_logging(self):
  152. """Make sure the :class:`coloredlogs.syslog.SystemLogging` context manager works."""
  153. system_log_file = self.find_system_log()
  154. expected_message = random_string(50)
  155. with SystemLogging(programname='coloredlogs-test-suite') as syslog:
  156. if not syslog:
  157. return self.skipTest("couldn't connect to syslog daemon")
  158. # When I tried out the system logging support on macOS 10.13.1 on
  159. # 2018-01-05 I found that while WARNING and ERROR messages show up
  160. # in the system log DEBUG and INFO messages don't. This explains
  161. # the importance of the level of the log message below.
  162. logging.error("%s", expected_message)
  163. # Retry the following assertion (for up to 60 seconds) to give the
  164. # logging daemon time to write our log message to disk. This
  165. # appears to be needed on MacOS workers on Travis CI, see:
  166. # https://travis-ci.org/xolox/python-coloredlogs/jobs/325245853
  167. retry(lambda: check_contents(system_log_file, expected_message, True))
  168. def test_system_logging_override(self):
  169. """Make sure the :class:`coloredlogs.syslog.is_syslog_supported` respects the override."""
  170. with PatchedItem(os.environ, 'COLOREDLOGS_SYSLOG', 'true'):
  171. assert is_syslog_supported() is True
  172. with PatchedItem(os.environ, 'COLOREDLOGS_SYSLOG', 'false'):
  173. assert is_syslog_supported() is False
  174. def test_syslog_shortcut_simple(self):
  175. """Make sure that ``coloredlogs.install(syslog=True)`` works."""
  176. system_log_file = self.find_system_log()
  177. expected_message = random_string(50)
  178. with cleanup_handlers():
  179. # See test_system_logging() for the importance of this log level.
  180. coloredlogs.install(syslog=True)
  181. logging.error("%s", expected_message)
  182. # See the comments in test_system_logging() on why this is retried.
  183. retry(lambda: check_contents(system_log_file, expected_message, True))
  184. def test_syslog_shortcut_enhanced(self):
  185. """Make sure that ``coloredlogs.install(syslog='warning')`` works."""
  186. system_log_file = self.find_system_log()
  187. the_expected_message = random_string(50)
  188. not_an_expected_message = random_string(50)
  189. with cleanup_handlers():
  190. # See test_system_logging() for the importance of these log levels.
  191. coloredlogs.install(syslog='error')
  192. logging.warning("%s", not_an_expected_message)
  193. logging.error("%s", the_expected_message)
  194. # See the comments in test_system_logging() on why this is retried.
  195. retry(lambda: check_contents(system_log_file, the_expected_message, True))
  196. retry(lambda: check_contents(system_log_file, not_an_expected_message, False))
  197. def test_name_normalization(self):
  198. """Make sure :class:`~coloredlogs.NameNormalizer` works as intended."""
  199. nn = NameNormalizer()
  200. for canonical_name in ['debug', 'info', 'warning', 'error', 'critical']:
  201. assert nn.normalize_name(canonical_name) == canonical_name
  202. assert nn.normalize_name(canonical_name.upper()) == canonical_name
  203. assert nn.normalize_name('warn') == 'warning'
  204. assert nn.normalize_name('fatal') == 'critical'
  205. def test_style_parsing(self):
  206. """Make sure :func:`~coloredlogs.parse_encoded_styles()` works as intended."""
  207. encoded_styles = 'debug=green;warning=yellow;error=red;critical=red,bold'
  208. decoded_styles = parse_encoded_styles(encoded_styles, normalize_key=lambda k: k.upper())
  209. assert sorted(decoded_styles.keys()) == sorted(['debug', 'warning', 'error', 'critical'])
  210. assert decoded_styles['debug']['color'] == 'green'
  211. assert decoded_styles['warning']['color'] == 'yellow'
  212. assert decoded_styles['error']['color'] == 'red'
  213. assert decoded_styles['critical']['color'] == 'red'
  214. assert decoded_styles['critical']['bold'] is True
  215. def test_is_verbose(self):
  216. """Make sure is_verbose() does what it should :-)."""
  217. set_level(logging.INFO)
  218. assert not is_verbose()
  219. set_level(logging.DEBUG)
  220. assert is_verbose()
  221. set_level(logging.VERBOSE)
  222. assert is_verbose()
  223. def test_increase_verbosity(self):
  224. """Make sure increase_verbosity() respects default and custom levels."""
  225. # Start from a known state.
  226. set_level(logging.INFO)
  227. assert get_level() == logging.INFO
  228. # INFO -> VERBOSE.
  229. increase_verbosity()
  230. assert get_level() == logging.VERBOSE
  231. # VERBOSE -> DEBUG.
  232. increase_verbosity()
  233. assert get_level() == logging.DEBUG
  234. # DEBUG -> SPAM.
  235. increase_verbosity()
  236. assert get_level() == logging.SPAM
  237. # SPAM -> NOTSET.
  238. increase_verbosity()
  239. assert get_level() == logging.NOTSET
  240. # NOTSET -> NOTSET.
  241. increase_verbosity()
  242. assert get_level() == logging.NOTSET
  243. def test_decrease_verbosity(self):
  244. """Make sure decrease_verbosity() respects default and custom levels."""
  245. # Start from a known state.
  246. set_level(logging.INFO)
  247. assert get_level() == logging.INFO
  248. # INFO -> NOTICE.
  249. decrease_verbosity()
  250. assert get_level() == logging.NOTICE
  251. # NOTICE -> WARNING.
  252. decrease_verbosity()
  253. assert get_level() == logging.WARNING
  254. # WARNING -> SUCCESS.
  255. decrease_verbosity()
  256. assert get_level() == logging.SUCCESS
  257. # SUCCESS -> ERROR.
  258. decrease_verbosity()
  259. assert get_level() == logging.ERROR
  260. # ERROR -> CRITICAL.
  261. decrease_verbosity()
  262. assert get_level() == logging.CRITICAL
  263. # CRITICAL -> CRITICAL.
  264. decrease_verbosity()
  265. assert get_level() == logging.CRITICAL
  266. def test_level_discovery(self):
  267. """Make sure find_defined_levels() always reports the levels defined in Python's standard library."""
  268. defined_levels = find_defined_levels()
  269. level_values = defined_levels.values()
  270. for number in (0, 10, 20, 30, 40, 50):
  271. assert number in level_values
  272. def test_walk_propagation_tree(self):
  273. """Make sure walk_propagation_tree() properly walks the tree of loggers."""
  274. root, parent, child, grand_child = self.get_logger_tree()
  275. # Check the default mode of operation.
  276. loggers = list(walk_propagation_tree(grand_child))
  277. assert loggers == [grand_child, child, parent, root]
  278. # Now change the propagation (non-default mode of operation).
  279. child.propagate = False
  280. loggers = list(walk_propagation_tree(grand_child))
  281. assert loggers == [grand_child, child]
  282. def test_find_handler(self):
  283. """Make sure find_handler() works as intended."""
  284. root, parent, child, grand_child = self.get_logger_tree()
  285. # Add some handlers to the tree.
  286. stream_handler = logging.StreamHandler()
  287. syslog_handler = logging.handlers.SysLogHandler()
  288. child.addHandler(stream_handler)
  289. parent.addHandler(syslog_handler)
  290. # Make sure the first matching handler is returned.
  291. matched_handler, matched_logger = find_handler(grand_child, lambda h: isinstance(h, logging.Handler))
  292. assert matched_handler is stream_handler
  293. # Make sure the first matching handler of the given type is returned.
  294. matched_handler, matched_logger = find_handler(child, lambda h: isinstance(h, logging.handlers.SysLogHandler))
  295. assert matched_handler is syslog_handler
  296. def get_logger_tree(self):
  297. """Create and return a tree of loggers."""
  298. # Get the root logger.
  299. root = logging.getLogger()
  300. # Create a top level logger for ourselves.
  301. parent_name = random_string()
  302. parent = logging.getLogger(parent_name)
  303. # Create a child logger.
  304. child_name = '%s.%s' % (parent_name, random_string())
  305. child = logging.getLogger(child_name)
  306. # Create a grand child logger.
  307. grand_child_name = '%s.%s' % (child_name, random_string())
  308. grand_child = logging.getLogger(grand_child_name)
  309. return root, parent, child, grand_child
  310. def test_support_for_milliseconds(self):
  311. """Make sure milliseconds are hidden by default but can be easily enabled."""
  312. # Check that the default log format doesn't include milliseconds.
  313. stream = StringIO()
  314. install(reconfigure=True, stream=stream)
  315. logging.info("This should not include milliseconds.")
  316. assert all(map(PLAIN_TEXT_PATTERN.match, stream.getvalue().splitlines()))
  317. # Check that milliseconds can be enabled via a shortcut.
  318. stream = StringIO()
  319. install(milliseconds=True, reconfigure=True, stream=stream)
  320. logging.info("This should include milliseconds.")
  321. assert all(map(PATTERN_INCLUDING_MILLISECONDS.match, stream.getvalue().splitlines()))
  322. def test_support_for_milliseconds_directive(self):
  323. """Make sure milliseconds using the ``%f`` directive are supported."""
  324. stream = StringIO()
  325. install(reconfigure=True, stream=stream, datefmt='%Y-%m-%dT%H:%M:%S.%f%z')
  326. logging.info("This should be timestamped according to #45.")
  327. assert re.match(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}[+-]\d{4}\s', stream.getvalue())
  328. def test_plain_text_output_format(self):
  329. """Inspect the plain text output of coloredlogs."""
  330. logger = VerboseLogger(random_string(25))
  331. stream = StringIO()
  332. install(level=logging.NOTSET, logger=logger, stream=stream)
  333. # Test that filtering on severity works.
  334. logger.setLevel(logging.INFO)
  335. logger.debug("No one should see this message.")
  336. assert len(stream.getvalue().strip()) == 0
  337. # Test that the default output format looks okay in plain text.
  338. logger.setLevel(logging.NOTSET)
  339. for method, severity in ((logger.debug, 'DEBUG'),
  340. (logger.info, 'INFO'),
  341. (logger.verbose, 'VERBOSE'),
  342. (logger.warning, 'WARNING'),
  343. (logger.error, 'ERROR'),
  344. (logger.critical, 'CRITICAL')):
  345. # XXX Workaround for a regression in Python 3.7 caused by the
  346. # Logger.isEnabledFor() method using stale cache entries. If we
  347. # don't clear the cache then logger.isEnabledFor(logging.DEBUG)
  348. # returns False and no DEBUG message is emitted.
  349. try:
  350. logger._cache.clear()
  351. except AttributeError:
  352. pass
  353. # Prepare the text.
  354. text = "This is a message with severity %r." % severity.lower()
  355. # Log the message with the given severity.
  356. method(text)
  357. # Get the line of output generated by the handler.
  358. output = stream.getvalue()
  359. lines = output.splitlines()
  360. last_line = lines[-1]
  361. assert text in last_line
  362. assert severity in last_line
  363. assert PLAIN_TEXT_PATTERN.match(last_line)
  364. def test_dynamic_stderr_lookup(self):
  365. """Make sure coloredlogs.install() uses StandardErrorHandler when possible."""
  366. coloredlogs.install()
  367. # Redirect sys.stderr to a temporary buffer.
  368. initial_stream = StringIO()
  369. initial_text = "Which stream will receive this text?"
  370. with PatchedAttribute(sys, 'stderr', initial_stream):
  371. logging.info(initial_text)
  372. assert initial_text in initial_stream.getvalue()
  373. # Redirect sys.stderr again, to a different destination.
  374. subsequent_stream = StringIO()
  375. subsequent_text = "And which stream will receive this other text?"
  376. with PatchedAttribute(sys, 'stderr', subsequent_stream):
  377. logging.info(subsequent_text)
  378. assert subsequent_text in subsequent_stream.getvalue()
  379. def test_force_enable(self):
  380. """Make sure ANSI escape sequences can be forced (bypassing auto-detection)."""
  381. interpreter = subprocess.Popen([
  382. sys.executable, "-c", ";".join([
  383. "import coloredlogs, logging",
  384. "coloredlogs.install(isatty=True)",
  385. "logging.info('Hello world')",
  386. ]),
  387. ], stderr=subprocess.PIPE)
  388. stdout, stderr = interpreter.communicate()
  389. assert ANSI_CSI in stderr.decode('UTF-8')
  390. def test_auto_disable(self):
  391. """
  392. Make sure ANSI escape sequences are not emitted when logging output is being redirected.
  393. This is a regression test for https://github.com/xolox/python-coloredlogs/issues/100.
  394. It works as follows:
  395. 1. We mock an interactive terminal using 'capturer' to ensure that this
  396. test works inside test drivers that capture output (like pytest).
  397. 2. We launch a subprocess (to ensure a clean process state) where
  398. stderr is captured but stdout is not, emulating issue #100.
  399. 3. The output captured on stderr contained ANSI escape sequences after
  400. this test was written and before the issue was fixed, so now this
  401. serves as a regression test for issue #100.
  402. """
  403. with CaptureOutput():
  404. interpreter = subprocess.Popen([
  405. sys.executable, "-c", ";".join([
  406. "import coloredlogs, logging",
  407. "coloredlogs.install()",
  408. "logging.info('Hello world')",
  409. ]),
  410. ], stderr=subprocess.PIPE)
  411. stdout, stderr = interpreter.communicate()
  412. assert ANSI_CSI not in stderr.decode('UTF-8')
  413. def test_env_disable(self):
  414. """Make sure ANSI escape sequences can be disabled using ``$NO_COLOR``."""
  415. with PatchedItem(os.environ, 'NO_COLOR', 'I like monochrome'):
  416. with CaptureOutput() as capturer:
  417. subprocess.check_call([
  418. sys.executable, "-c", ";".join([
  419. "import coloredlogs, logging",
  420. "coloredlogs.install()",
  421. "logging.info('Hello world')",
  422. ]),
  423. ])
  424. output = capturer.get_text()
  425. assert ANSI_CSI not in output
  426. def test_html_conversion(self):
  427. """Check the conversion from ANSI escape sequences to HTML."""
  428. # Check conversion of colored text.
  429. for color_name, ansi_code in ANSI_COLOR_CODES.items():
  430. ansi_encoded_text = 'plain text followed by %s text' % ansi_wrap(color_name, color=color_name)
  431. expected_html = format(
  432. '<code>plain text followed by <span style="color:{css}">{name}</span> text</code>',
  433. css=EIGHT_COLOR_PALETTE[ansi_code], name=color_name,
  434. )
  435. self.assertEqual(expected_html, convert(ansi_encoded_text))
  436. # Check conversion of bright colored text.
  437. expected_html = '<code><span style="color:#FF0">bright yellow</span></code>'
  438. self.assertEqual(expected_html, convert(ansi_wrap('bright yellow', color='yellow', bright=True)))
  439. # Check conversion of text with a background color.
  440. expected_html = '<code><span style="background-color:#DE382B">red background</span></code>'
  441. self.assertEqual(expected_html, convert(ansi_wrap('red background', background='red')))
  442. # Check conversion of text with a bright background color.
  443. expected_html = '<code><span style="background-color:#F00">bright red background</span></code>'
  444. self.assertEqual(expected_html, convert(ansi_wrap('bright red background', background='red', bright=True)))
  445. # Check conversion of text that uses the 256 color mode palette as a foreground color.
  446. expected_html = '<code><span style="color:#FFAF00">256 color mode foreground</span></code>'
  447. self.assertEqual(expected_html, convert(ansi_wrap('256 color mode foreground', color=214)))
  448. # Check conversion of text that uses the 256 color mode palette as a background color.
  449. expected_html = '<code><span style="background-color:#AF0000">256 color mode background</span></code>'
  450. self.assertEqual(expected_html, convert(ansi_wrap('256 color mode background', background=124)))
  451. # Check that invalid 256 color mode indexes don't raise exceptions.
  452. expected_html = '<code>plain text expected</code>'
  453. self.assertEqual(expected_html, convert('\x1b[38;5;256mplain text expected\x1b[0m'))
  454. # Check conversion of bold text.
  455. expected_html = '<code><span style="font-weight:bold">bold text</span></code>'
  456. self.assertEqual(expected_html, convert(ansi_wrap('bold text', bold=True)))
  457. # Check conversion of underlined text.
  458. expected_html = '<code><span style="text-decoration:underline">underlined text</span></code>'
  459. self.assertEqual(expected_html, convert(ansi_wrap('underlined text', underline=True)))
  460. # Check conversion of strike-through text.
  461. expected_html = '<code><span style="text-decoration:line-through">strike-through text</span></code>'
  462. self.assertEqual(expected_html, convert(ansi_wrap('strike-through text', strike_through=True)))
  463. # Check conversion of inverse text.
  464. expected_html = '<code><span style="background-color:#FFC706;color:#000">inverse</span></code>'
  465. self.assertEqual(expected_html, convert(ansi_wrap('inverse', color='yellow', inverse=True)))
  466. # Check conversion of URLs.
  467. for sample_text in 'www.python.org', 'http://coloredlogs.rtfd.org', 'https://coloredlogs.rtfd.org':
  468. sample_url = sample_text if '://' in sample_text else ('http://' + sample_text)
  469. expected_html = '<code><a href="%s" style="color:inherit">%s</a></code>' % (sample_url, sample_text)
  470. self.assertEqual(expected_html, convert(sample_text))
  471. # Check that the capture pattern for URLs doesn't match ANSI escape
  472. # sequences and also check that the short hand for the 0 reset code is
  473. # supported. These are tests for regressions of bugs found in
  474. # coloredlogs <= 8.0.
  475. reset_short_hand = '\x1b[0m'
  476. blue_underlined = ansi_style(color='blue', underline=True)
  477. ansi_encoded_text = '<%shttps://coloredlogs.readthedocs.io%s>' % (blue_underlined, reset_short_hand)
  478. expected_html = (
  479. '<code>&lt;<span style="color:#006FB8;text-decoration:underline">'
  480. '<a href="https://coloredlogs.readthedocs.io" style="color:inherit">'
  481. 'https://coloredlogs.readthedocs.io'
  482. '</a></span>&gt;</code>'
  483. )
  484. self.assertEqual(expected_html, convert(ansi_encoded_text))
  485. def test_output_interception(self):
  486. """Test capturing of output from external commands."""
  487. expected_output = 'testing, 1, 2, 3 ..'
  488. actual_output = capture(['echo', expected_output])
  489. assert actual_output.strip() == expected_output.strip()
  490. def test_enable_colored_cron_mailer(self):
  491. """Test that automatic ANSI to HTML conversion when running under ``cron`` can be enabled."""
  492. with PatchedItem(os.environ, 'CONTENT_TYPE', 'text/html'):
  493. with ColoredCronMailer() as mailer:
  494. assert mailer.is_enabled
  495. def test_disable_colored_cron_mailer(self):
  496. """Test that automatic ANSI to HTML conversion when running under ``cron`` can be disabled."""
  497. with PatchedItem(os.environ, 'CONTENT_TYPE', 'text/plain'):
  498. with ColoredCronMailer() as mailer:
  499. assert not mailer.is_enabled
  500. def test_auto_install(self):
  501. """Test :func:`coloredlogs.auto_install()`."""
  502. needle = random_string()
  503. command_line = [sys.executable, '-c', 'import logging; logging.info(%r)' % needle]
  504. # Sanity check that log messages aren't enabled by default.
  505. with CaptureOutput() as capturer:
  506. os.environ['COLOREDLOGS_AUTO_INSTALL'] = 'false'
  507. subprocess.check_call(command_line)
  508. output = capturer.get_text()
  509. assert needle not in output
  510. # Test that the $COLOREDLOGS_AUTO_INSTALL environment variable can be
  511. # used to automatically call coloredlogs.install() during initialization.
  512. with CaptureOutput() as capturer:
  513. os.environ['COLOREDLOGS_AUTO_INSTALL'] = 'true'
  514. subprocess.check_call(command_line)
  515. output = capturer.get_text()
  516. assert needle in output
  517. def test_cli_demo(self):
  518. """Test the command line colored logging demonstration."""
  519. with CaptureOutput() as capturer:
  520. main('coloredlogs', '--demo')
  521. output = capturer.get_text()
  522. # Make sure the output contains all of the expected logging level names.
  523. for name in 'debug', 'info', 'warning', 'error', 'critical':
  524. assert name.upper() in output
  525. def test_cli_conversion(self):
  526. """Test the command line HTML conversion."""
  527. output = main('coloredlogs', '--convert', 'coloredlogs', '--demo', capture=True)
  528. # Make sure the output is encoded as HTML.
  529. assert '<span' in output
  530. def test_empty_conversion(self):
  531. """
  532. Test that conversion of empty output produces no HTML.
  533. This test was added because I found that ``coloredlogs --convert`` when
  534. used in a cron job could cause cron to send out what appeared to be
  535. empty emails. On more careful inspection the body of those emails was
  536. ``<code></code>``. By not emitting the wrapper element when no other
  537. HTML is generated, cron will not send out an email.
  538. """
  539. output = main('coloredlogs', '--convert', 'true', capture=True)
  540. assert not output.strip()
  541. def test_implicit_usage_message(self):
  542. """Test that the usage message is shown when no actions are given."""
  543. assert 'Usage:' in main('coloredlogs', capture=True)
  544. def test_explicit_usage_message(self):
  545. """Test that the usage message is shown when ``--help`` is given."""
  546. assert 'Usage:' in main('coloredlogs', '--help', capture=True)
  547. def test_custom_record_factory(self):
  548. """
  549. Test that custom LogRecord factories are supported.
  550. This test is a bit convoluted because the logging module suppresses
  551. exceptions. We monkey patch the method suspected of encountering
  552. exceptions so that we can tell after it was called whether any
  553. exceptions occurred (despite the exceptions not propagating).
  554. """
  555. if not hasattr(logging, 'getLogRecordFactory'):
  556. return self.skipTest("this test requires Python >= 3.2")
  557. exceptions = []
  558. original_method = ColoredFormatter.format
  559. original_factory = logging.getLogRecordFactory()
  560. def custom_factory(*args, **kwargs):
  561. record = original_factory(*args, **kwargs)
  562. record.custom_attribute = 0xdecafbad
  563. return record
  564. def custom_method(*args, **kw):
  565. try:
  566. return original_method(*args, **kw)
  567. except Exception as e:
  568. exceptions.append(e)
  569. raise
  570. with PatchedAttribute(ColoredFormatter, 'format', custom_method):
  571. logging.setLogRecordFactory(custom_factory)
  572. try:
  573. demonstrate_colored_logging()
  574. finally:
  575. logging.setLogRecordFactory(original_factory)
  576. # Ensure that no exceptions were triggered.
  577. assert not exceptions
  578. def check_contents(filename, contents, match):
  579. """Check if a line in a file contains an expected string."""
  580. with open(filename) as handle:
  581. assert any(contents in line for line in handle) == match
  582. def main(*arguments, **options):
  583. """Wrap the command line interface to make it easier to test."""
  584. capture = options.get('capture', False)
  585. saved_argv = sys.argv
  586. saved_stdout = sys.stdout
  587. try:
  588. sys.argv = arguments
  589. if capture:
  590. sys.stdout = StringIO()
  591. coloredlogs.cli.main()
  592. if capture:
  593. return sys.stdout.getvalue()
  594. finally:
  595. sys.argv = saved_argv
  596. sys.stdout = saved_stdout
  597. @contextlib.contextmanager
  598. def cleanup_handlers():
  599. """Context manager to cleanup output handlers."""
  600. # There's nothing to set up so we immediately yield control.
  601. yield
  602. # After the with block ends we cleanup any output handlers.
  603. for match_func in match_stream_handler, match_syslog_handler:
  604. handler, logger = find_handler(logging.getLogger(), match_func)
  605. if handler and logger:
  606. logger.removeHandler(handler)