PageRenderTime 52ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/external/webkit/Tools/Scripts/webkitpy/common/system/logtesting.py

https://gitlab.com/brian0218/rk3188_r-box_android4.2.2_sdk
Python | 258 lines | 162 code | 14 blank | 82 comment | 0 complexity | 530fd5f4cf27b98ac075b31a744e1787 MD5 | raw file
  1. # Copyright (C) 2010 Chris Jerdonek (cjerdonek@webkit.org)
  2. #
  3. # Redistribution and use in source and binary forms, with or without
  4. # modification, are permitted provided that the following conditions
  5. # are met:
  6. # 1. Redistributions of source code must retain the above copyright
  7. # notice, this list of conditions and the following disclaimer.
  8. # 2. Redistributions in binary form must reproduce the above copyright
  9. # notice, this list of conditions and the following disclaimer in the
  10. # documentation and/or other materials provided with the distribution.
  11. #
  12. # THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND
  13. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  14. # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  15. # DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
  16. # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  17. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  18. # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  19. # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  20. # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  21. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  22. """Supports the unit-testing of logging code.
  23. Provides support for unit-testing messages logged using the built-in
  24. logging module.
  25. Inherit from the LoggingTestCase class for basic testing needs. For
  26. more advanced needs (e.g. unit-testing methods that configure logging),
  27. see the TestLogStream class, and perhaps also the LogTesting class.
  28. """
  29. import logging
  30. import unittest
  31. class TestLogStream(object):
  32. """Represents a file-like object for unit-testing logging.
  33. This is meant for passing to the logging.StreamHandler constructor.
  34. Log messages captured by instances of this object can be tested
  35. using self.assertMessages() below.
  36. """
  37. def __init__(self, test_case):
  38. """Create an instance.
  39. Args:
  40. test_case: A unittest.TestCase instance.
  41. """
  42. self._test_case = test_case
  43. self.messages = []
  44. """A list of log messages written to the stream."""
  45. # Python documentation says that any object passed to the StreamHandler
  46. # constructor should support write() and flush():
  47. #
  48. # http://docs.python.org/library/logging.html#module-logging.handlers
  49. def write(self, message):
  50. self.messages.append(message)
  51. def flush(self):
  52. pass
  53. def assertMessages(self, messages):
  54. """Assert that the given messages match the logged messages.
  55. messages: A list of log message strings.
  56. """
  57. self._test_case.assertEquals(messages, self.messages)
  58. class LogTesting(object):
  59. """Supports end-to-end unit-testing of log messages.
  60. Sample usage:
  61. class SampleTest(unittest.TestCase):
  62. def setUp(self):
  63. self._log = LogTesting.setUp(self) # Turn logging on.
  64. def tearDown(self):
  65. self._log.tearDown() # Turn off and reset logging.
  66. def test_logging_in_some_method(self):
  67. call_some_method() # Contains calls to _log.info(), etc.
  68. # Check the resulting log messages.
  69. self._log.assertMessages(["INFO: expected message #1",
  70. "WARNING: expected message #2"])
  71. """
  72. def __init__(self, test_stream, handler):
  73. """Create an instance.
  74. This method should never be called directly. Instances should
  75. instead be created using the static setUp() method.
  76. Args:
  77. test_stream: A TestLogStream instance.
  78. handler: The handler added to the logger.
  79. """
  80. self._test_stream = test_stream
  81. self._handler = handler
  82. @staticmethod
  83. def _getLogger():
  84. """Return the logger being tested."""
  85. # It is possible we might want to return something other than
  86. # the root logger in some special situation. For now, the
  87. # root logger seems to suffice.
  88. return logging.getLogger()
  89. @staticmethod
  90. def setUp(test_case, logging_level=logging.INFO):
  91. """Configure logging for unit testing.
  92. Configures the root logger to log to a testing log stream.
  93. Only messages logged at or above the given level are logged
  94. to the stream. Messages logged to the stream are formatted
  95. in the following way, for example--
  96. "INFO: This is a test log message."
  97. This method should normally be called in the setUp() method
  98. of a unittest.TestCase. See the docstring of this class
  99. for more details.
  100. Returns:
  101. A LogTesting instance.
  102. Args:
  103. test_case: A unittest.TestCase instance.
  104. logging_level: An integer logging level that is the minimum level
  105. of log messages you would like to test.
  106. """
  107. stream = TestLogStream(test_case)
  108. handler = logging.StreamHandler(stream)
  109. handler.setLevel(logging_level)
  110. formatter = logging.Formatter("%(levelname)s: %(message)s")
  111. handler.setFormatter(formatter)
  112. # Notice that we only change the root logger by adding a handler
  113. # to it. In particular, we do not reset its level using
  114. # logger.setLevel(). This ensures that we have not interfered
  115. # with how the code being tested may have configured the root
  116. # logger.
  117. logger = LogTesting._getLogger()
  118. logger.addHandler(handler)
  119. return LogTesting(stream, handler)
  120. def tearDown(self):
  121. """Assert there are no remaining log messages, and reset logging.
  122. This method asserts that there are no more messages in the array of
  123. log messages, and then restores logging to its original state.
  124. This method should normally be called in the tearDown() method of a
  125. unittest.TestCase. See the docstring of this class for more details.
  126. """
  127. self.assertMessages([])
  128. logger = LogTesting._getLogger()
  129. logger.removeHandler(self._handler)
  130. def messages(self):
  131. """Return the current list of log messages."""
  132. return self._test_stream.messages
  133. # FIXME: Add a clearMessages() method for cases where the caller
  134. # deliberately doesn't want to assert every message.
  135. # We clear the log messages after asserting since they are no longer
  136. # needed after asserting. This serves two purposes: (1) it simplifies
  137. # the calling code when we want to check multiple logging calls in a
  138. # single test method, and (2) it lets us check in the tearDown() method
  139. # that there are no remaining log messages to be asserted.
  140. #
  141. # The latter ensures that no extra log messages are getting logged that
  142. # the caller might not be aware of or may have forgotten to check for.
  143. # This gets us a bit more mileage out of our tests without writing any
  144. # additional code.
  145. def assertMessages(self, messages):
  146. """Assert the current array of log messages, and clear its contents.
  147. Args:
  148. messages: A list of log message strings.
  149. """
  150. try:
  151. self._test_stream.assertMessages(messages)
  152. finally:
  153. # We want to clear the array of messages even in the case of
  154. # an Exception (e.g. an AssertionError). Otherwise, another
  155. # AssertionError can occur in the tearDown() because the
  156. # array might not have gotten emptied.
  157. self._test_stream.messages = []
  158. # This class needs to inherit from unittest.TestCase. Otherwise, the
  159. # setUp() and tearDown() methods will not get fired for test case classes
  160. # that inherit from this class -- even if the class inherits from *both*
  161. # unittest.TestCase and LoggingTestCase.
  162. #
  163. # FIXME: Rename this class to LoggingTestCaseBase to be sure that
  164. # the unittest module does not interpret this class as a unittest
  165. # test case itself.
  166. class LoggingTestCase(unittest.TestCase):
  167. """Supports end-to-end unit-testing of log messages.
  168. Sample usage:
  169. class SampleTest(LoggingTestCase):
  170. def test_logging_in_some_method(self):
  171. call_some_method() # Contains calls to _log.info(), etc.
  172. # Check the resulting log messages.
  173. self.assertLog(["INFO: expected message #1",
  174. "WARNING: expected message #2"])
  175. """
  176. def setUp(self):
  177. self._log = LogTesting.setUp(self)
  178. def tearDown(self):
  179. self._log.tearDown()
  180. def logMessages(self):
  181. """Return the current list of log messages."""
  182. return self._log.messages()
  183. # FIXME: Add a clearMessages() method for cases where the caller
  184. # deliberately doesn't want to assert every message.
  185. # See the code comments preceding LogTesting.assertMessages() for
  186. # an explanation of why we clear the array of messages after
  187. # asserting its contents.
  188. def assertLog(self, messages):
  189. """Assert the current array of log messages, and clear its contents.
  190. Args:
  191. messages: A list of log message strings.
  192. """
  193. self._log.assertMessages(messages)