vendor/Five/1.2b-r20590

view testing/loghandler.py @ 0:3673ed425f80

Vendor import of Five 1.2b+ (r20590)
author fguillaume
date Fri, 02 Dec 2005 20:25:42 +0000
parents
children
line source
1 ##############################################################################
2 #
3 # Copyright (c) 2003 Zope Corporation and Contributors.
4 # All Rights Reserved.
5 #
6 # This software is subject to the provisions of the Zope Public License,
7 # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
8 # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
9 # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
10 # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
11 # FOR A PARTICULAR PURPOSE.
12 #
13 ##############################################################################
14 """logging handler for tests that check logging output.
16 $Id: loghandler.py 18831 2005-10-21 18:07:37Z yuppie $
17 """
18 import logging
20 class Handler(logging.Handler):
21 """Handler for use with unittest.TestCase objects.
23 The handler takes a TestCase instance as a constructor argument.
24 It can be registered with one or more loggers and collects log
25 records they generate.
27 The assertLogsMessage() and failIfLogsMessage() methods can be
28 used to check the logger output and causes the test to fail as
29 appropriate.
30 """
32 def __init__(self, testcase, propagate=False):
33 logging.Handler.__init__(self)
34 self.records = []
35 # loggers stores (logger, propagate) tuples
36 self.loggers = []
37 self.closed = False
38 self.propagate = propagate
39 self.testcase = testcase
41 def close(self):
42 """Remove handler from any loggers it was added to."""
43 if self.closed:
44 return
45 for logger, propagate in self.loggers:
46 logger.removeHandler(self)
47 logger.propagate = propagate
48 self.closed = True
50 def add(self, name):
51 """Add handler to logger named name."""
52 logger = logging.getLogger(name)
53 old_prop = logger.propagate
54 logger.addHandler(self)
55 if self.propagate:
56 logger.propagate = 1
57 else:
58 logger.propagate = 0
59 self.loggers.append((logger, old_prop))
61 def emit(self, record):
62 self.records.append(record)
64 def assertLogsMessage(self, msg, level=None):
65 for r in self.records:
66 if r.getMessage() == msg:
67 if level is not None and r.levelno == level:
68 return
69 msg = "No log message contained %r" % msg
70 if level is not None:
71 msg += " at level %d" % level
72 self.testcase.fail(msg)
74 def failIfLogsMessage(self, msg):
75 for r in self.records:
76 if r.getMessage() == msg:
77 self.testcase.fail("Found log message %r" % msg)