Skip to content

Commit

Permalink
Merge pull request #51 from redtoad/master
Browse files Browse the repository at this point in the history
Make TestHandler.has_warning(...) less strict
  • Loading branch information
Roman Valls committed Oct 28, 2012
2 parents 3d9e982 + e1259c9 commit 65ad7b4
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
5 changes: 4 additions & 1 deletion docs/unittesting.rst
Expand Up @@ -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
Expand All @@ -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')
Expand Down
12 changes: 11 additions & 1 deletion logbook/handlers.py
Expand Up @@ -9,6 +9,7 @@
:license: BSD, see LICENSE for more details.
"""
import os
import re
import sys
import stat
import errno
Expand Down Expand Up @@ -71,6 +72,8 @@

SYSLOG_PORT = 514

REGTYPE = type(re.compile("I'm a regular expression!"))

_py3 = sys.version_info >= (3, 0)


Expand Down Expand Up @@ -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
Expand Down
11 changes: 11 additions & 0 deletions logbook/testsuite/test_regular.py
Expand Up @@ -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):
Expand Down

0 comments on commit 65ad7b4

Please sign in to comment.