gbplogtester.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # vim: set fileencoding=utf-8 :
  2. import re
  3. from six import StringIO
  4. from nose.tools import ok_
  5. import gbp.log
  6. class GbpLogTester(object):
  7. """
  8. Helper class for tests that need to capture logging output
  9. """
  10. def __init__(self):
  11. """Object initialization"""
  12. self._log = None
  13. self._loghandler = None
  14. def _capture_log(self, capture=True):
  15. """ Capture log"""
  16. if capture:
  17. assert self._log is None, "Log capture already started"
  18. self._log = StringIO()
  19. self._loghandler = gbp.log.GbpStreamHandler(self._log, False)
  20. self._loghandler.addFilter(gbp.log.GbpFilter([gbp.log.WARNING,
  21. gbp.log.ERROR]))
  22. handlers = list(gbp.log.LOGGER.handlers)
  23. for hdl in handlers:
  24. gbp.log.LOGGER.removeHandler(hdl)
  25. gbp.log.LOGGER.addHandler(self._loghandler)
  26. else:
  27. assert self._log is not None, "Log capture not started"
  28. gbp.log.LOGGER.removeHandler(self._loghandler)
  29. self._loghandler.close()
  30. self._loghandler = None
  31. self._log.close()
  32. self._log = None
  33. def _get_log(self):
  34. """Get the captured log output"""
  35. self._log.seek(0)
  36. return self._log.readlines()
  37. def _check_log_empty(self):
  38. """Check that nothig was logged"""
  39. output = self._get_log()
  40. ok_(output == [], "Log is not empty: %s" % output)
  41. def _check_log(self, linenum, regex):
  42. """Check that the specified line on log matches expectations"""
  43. if self._log is None:
  44. raise Exception("BUG in unittests: no log captured!")
  45. output = self._get_log()[linenum].strip()
  46. ok_(re.match(regex, output),
  47. "Log entry '%s' doesn't match '%s'" % (output, regex))
  48. def _clear_log(self):
  49. """Clear the mock strerr"""
  50. if self._log is not None:
  51. self._log.seek(0)
  52. self._log.truncate()