summaryrefslogtreecommitdiff
path: root/lib/fixtures/_fixtures/logger.py
blob: 4b85b2215100fd3e02aed2b58b001b0a0a18cfe5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#  fixtures: Fixtures with cleanups for testing and convenience.
#
# Copyright (c) 2011, Robert Collins <robertc@robertcollins.net>
#
# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause
# license at the users choice. A copy of both licenses are available in the
# project source as Apache-2.0 and BSD. You may not use this file except in
# compliance with one of these two licences.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under these licenses is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
# license you chose for the specific language governing permissions and
# limitations under that license.

from logging import StreamHandler, getLogger, INFO, Formatter
from cStringIO import StringIO

from testtools.content import Content
from testtools.content_type import UTF8_TEXT

from fixtures import Fixture

__all__ = [
    'FakeLogger',
    'LoggerFixture',
    ]


class FakeLogger(Fixture):
    """Replace a logger and capture its output."""

    def __init__(self, name="", level=INFO, format=None, nuke_handlers=True):
        """Create a FakeLogger fixture.

        :param name: The name of the logger to replace. Defaults to "".
        :param level: The log level to set, defaults to INFO.
        :param format: Logging format to use. Defaults to capturing supplied
            messages verbatim.
        :param nuke_handlers: If True remove all existing handles (prevents
            existing messages going to e.g. stdout). Defaults to True.

        Example:

          def test_log(self)
              fixture = self.useFixture(LoggerFixture())
              logging.info('message')
              self.assertEqual('message', fixture.output)
        """
        super(FakeLogger, self).__init__()
        self._name = name
        self._level = level
        self._format = format
        self._nuke_handlers = nuke_handlers

    def setUp(self):
        super(FakeLogger, self).setUp()
        output = StringIO()
        self.addDetail(
            u"pythonlogging:'%s'" % self._name,
            Content(UTF8_TEXT, lambda: [output.getvalue()]))
        self._output = output
        logger = getLogger(self._name)
        if self._level:
            self.addCleanup(logger.setLevel, logger.level)
            logger.setLevel(self._level)
        if self._nuke_handlers:
            for handler in reversed(logger.handlers):
                logger.removeHandler(handler)
                self.addCleanup(logger.addHandler, handler)
        handler = StreamHandler(output)
        if self._format:
            handler.setFormatter(Formatter(self._format))
        try:
            logger.addHandler(handler)
        finally:
            self.addCleanup(logger.removeHandler, handler)

    @property
    def output(self):
        return self._output.getvalue()


LoggerFixture = FakeLogger