Permalink
Browse files

Merge pull request #51 from redtoad/master

Make TestHandler.has_warning(...) less strict
  • Loading branch information...
2 parents 3d9e982 + e1259c9 commit 65ad7b45a1a7b8d824d5b0bb6460ab7d2aa3b21d Roman Valls committed Oct 28, 2012
Showing with 26 additions and 2 deletions.
  1. +4 −1 docs/unittesting.rst
  2. +11 −1 logbook/handlers.py
  3. +11 −0 logbook/testsuite/test_regular.py
View
@@ -74,7 +74,8 @@ arguments:
`message`
If provided and not `None` it will check if there is at least one log
- record where the message matches.
+ record where the message matches. This can also be a compiled regular
+ expression.
`channel`
If provided and not `None` it will check if there is at least one log
@@ -84,6 +85,8 @@ Example usage:
>>> handler.has_warning('A different message')
False
+>>> handler.has_warning(re.compile('^Hello'))
+True
>>> handler.has_warning('Hello World', channel='Testing')
True
>>> handler.has_warning(channel='Testing')
View
@@ -9,6 +9,7 @@
:license: BSD, see LICENSE for more details.
"""
import os
+import re
import sys
import stat
import errno
@@ -71,6 +72,8 @@
SYSLOG_PORT = 514
+REGTYPE = type(re.compile("I'm a regular expression!"))
+
_py3 = sys.version_info >= (3, 0)
@@ -961,12 +964,19 @@ def has_debug(self, *args, **kwargs):
return self._test_for(*args, **kwargs)
def _test_for(self, message=None, channel=None, level=None):
+ def _match(needle, haystack):
+ "Matches both compiled regular expressions and strings"
+ if isinstance(needle, REGTYPE) and needle.search(haystack):
+ return True
+ if needle == haystack:
+ return True
+ return False
for record in self.records:
if level is not None and record.level != level:
continue
if channel is not None and record.channel != channel:
continue
- if message is not None and record.message != message:
+ if message is not None and not _match(message, record.message):
continue
return True
return False
@@ -562,6 +562,17 @@ def inject_extra(record):
'for /index.html [GET]' in mail)
self.assert_('1 / 0' in mail)
+ def test_regex_matching(self):
+ test_handler = logbook.TestHandler()
+ test_handler.push_thread()
+ try:
+ self.log.warn('Hello World!')
+ self.assert_(test_handler.has_warning(re.compile('^Hello')))
+ self.assert_(not test_handler.has_warning(re.compile('world$')))
+ self.assert_(not test_handler.has_warning('^Hello World'))
+ finally:
+ test_handler.pop_thread()
+
def test_custom_handling_test(self):
class MyTestHandler(logbook.TestHandler):
def handle(self, record):

0 comments on commit 65ad7b4

Please sign in to comment.