1
# Copyright 2010-2015 Canonical Ltd. This software is licensed under the
2
# GNU Lesser General Public License version 3 (see the file LICENSE).
4
"""Tests for the logging events."""
6
from __future__ import absolute_import, print_function
13
from zope.component import (
18
# This non-standard import is necessary to hook up the event system.
19
import zope.component.event # noqa: F401
20
from zope.event import notify
22
from lazr.sshserver.events import (
28
class ListHandler(logging.Handler):
29
"""Logging handler that just appends records to a list.
31
This handler isn't intended to be used by production code -- memory leak
32
city! -- instead it's useful for unit tests that want to make sure the
33
right events are being logged.
36
def __init__(self, logging_list):
37
"""Construct a `ListHandler`.
39
:param logging_list: A list that will be appended to. The handler
42
logging.Handler.__init__(self)
43
self._list = logging_list
45
def emit(self, record):
46
"""Append 'record' to the list."""
47
self._list.append(record)
50
class TestLoggingEvent(testtools.TestCase):
52
def assertLogs(self, records, function, *args, **kwargs):
53
"""Assert 'function' logs 'records' when run with the given args."""
55
handler = ListHandler(logged_events)
56
self.logger.addHandler(handler)
57
result = function(*args, **kwargs)
58
self.logger.removeHandler(handler)
60
[(record.levelno, record.getMessage())
61
for record in logged_events], records)
64
def assertEventLogs(self, record, logging_event):
65
self.assertLogs([record], notify, logging_event)
68
super(TestLoggingEvent, self).setUp()
69
logger = logging.getLogger(self.getUniqueString())
70
logger.setLevel(logging.DEBUG)
73
@adapter(ILoggingEvent)
74
def _log_event(event):
75
logger.log(event.level, event.message)
77
provideHandler(_log_event)
78
self.addCleanup(getGlobalSiteManager().unregisterHandler, _log_event)
81
event = LoggingEvent(logging.CRITICAL, "foo")
82
self.assertEventLogs((logging.CRITICAL, 'foo'), event)
84
def test_formatting(self):
85
event = LoggingEvent(logging.DEBUG, "foo: %(name)s", name="bar")
86
self.assertEventLogs((logging.DEBUG, 'foo: bar'), event)
88
def test_subclass(self):
89
class SomeEvent(LoggingEvent):
90
template = "%(something)s happened."
93
(logging.INFO, 'foo happened.'), SomeEvent(something='foo'))