Skip to content

Instantly share code, notes, and snippets.

Created May 6, 2022 18:32
Show Gist options
  • Save kergoth/3d24f8d6f15fcc335160ae6e75894b59 to your computer and use it in GitHub Desktop.
Save kergoth/3d24f8d6f15fcc335160ae6e75894b59 to your computer and use it in GitHub Desktop.
def my_handler(d, logger):
logger.warning('test_warning')'test note')
logger.error('test error')
logger.critical('test critical')
python testhandler() {
_, error, logs = run_config_handler(lambda l: my_handler(d, l))
if error is not None:
d.setVar('TEST_ERROR', str(error))
if logs:
d.setVar('TEST_LOGS', logs)
testhandler[eventmask] = "bb.event.ConfigParsed"
addhandler testhandler
python testhandler_output() {
logs = d.getVar('TEST_LOGS')
if logs:
for l in logs:
error = d.getVar('TEST_ERROR')
if error is not None:
testhandler_output[eventmask] = "bb.event.BuildStarted bb.event.SanityCheck"
addhandler testhandler_output
def run_config_handler(config_handler, logger=None):
import logging
class LogRecorder():
'''Context manager which captures log records for testing.
Example usage in a TestCase:
def capture_logs(self, logger):
return LogRecorder(logger)
def assertLogged(self, recorder, message):
self.assertIn(message, recorder)
def test_something(self):
# Do something which generates log messages
with self.capture_logs(logger) as l:
self.assertLogged(l, 'my message')
# Or
with LogRecorder(logger) as l:
self.assertIn('my message', l)
class LogHandler(logging.Handler):
def __init__(self, recorder):
self.recorder = recorder
def emit(self, record):
def __init__(self, logger):
self.logger = logger
self.handler = self.LogHandler(self)
self.logs = []
def __enter__(self):
self.old_handlers = self.logger.handlers
self.logger.handlers = [self.handler]
# self.logger.addHandler(self.handler)
return self
def __exit__(self, type, value, traceback):
self.logger.handlers = self.old_handlers
# self.logger.removeHandler(self.handler)
def __contains__(self, message):
messages = (l.getMessage() for l in self.logs)
return any(message in m for m in messages)
if logger is None:
logger = logging.Logger('BitBake')
recorder = LogRecorder(logger)
with recorder:
result = config_handler(logger)
except BaseException as exc:
return None, exc, recorder.logs
return result, None, recorder.logs
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment