Permalink
Browse files

improve filter testing

  • Loading branch information...
1 parent 6f52835 commit 6e3e64088f5b1c537df1058712f31f4dad8279bb @bukzor committed Apr 2, 2012
Showing with 46 additions and 73 deletions.
  1. +6 −1 cheetah/Compiler.py
  2. +11 −11 cheetah/Template.py
  3. +15 −46 cheetah/Tests/Filters.py
  4. +14 −15 cheetah/Tests/SyntaxAndOutput.py
View
@@ -1096,7 +1096,12 @@ def _addAutoCleanupCode(self):
self.addChunk('')
def addStop(self, expr=None):
- self.addChunk('return _dummyTrans and trans.response().getvalue() or ""')
+ if self.setting('autoAssignDummyTransactionToSelf'):
+ empty = None
+ else:
+ empty = ''
+
+ self.addChunk('return _dummyTrans and trans.response().getvalue() or %r' % empty)
def addMethArg(self, name, defVal=None):
self._argStringList.append( (name, defVal) )
View
@@ -1409,20 +1409,20 @@ def capture(self, function, *args, **kwargs):
retval = function(*args, **kwargs)
buffer = self.transaction.response().getvalue()
- if retval == '':
+ if retval is None:
# Template functions using transactions always return an empty
# string
return buffer
-
- # ...but this one didn't, which means either the function is a
- # plain Python function, or it's a template function that used
- # #return.
- # In the latter case, check that it didn't /both/ use #return /and/
- # try to write to the buffer. Without $capture but with a
- # transaction, such a function would normally write out /both/ its
- # contents /and/ its return value, and we're not going to do that.
- if buffer.strip():
- warnings.warn("Ignoring buffer contents due to use of #return in $capture(%r)" % function)
+ else:
+ # ...but this one didn't, which means either the function is a
+ # plain Python function, or it's a template function that used
+ # #return.
+ # In the latter case, check that it didn't /both/ use #return /and/
+ # try to write to the buffer. Without $capture but with a
+ # transaction, such a function would normally write out /both/ its
+ # contents /and/ its return value, and we're not going to do that.
+ if buffer.strip():
+ warnings.warn("Ignoring buffer contents due to use of #return in $capture(%r)" % function)
return retval
finally:
View
@@ -73,24 +73,11 @@ class UniqueFilter(Cheetah.Filters.Filter):
"""A dummy filter that tries to notice when it's been called twice on the
same string.
"""
+ count = 0
def filter(self, s, rawExpr=None):
- if s == '':
- # Defs return empty string when transactions are in use, and
- # filtering that is harmless
- return s
-
- # Strip off any whitespace template cruft
- s = s.strip()
- if '@' in s:
- raise UniqueError("UniqueFilter applied twice to the same string; got %r" % (s,))
- return '@' + s
-
- @classmethod
- def unfilter(cls, s):
- """Removes the decoration, allowing the string to be filtered again
- without incident.
- """
- return s.replace('@', '')
+ self.count += 1
+ return '<%i>%s</%i>' % (self.count, s, self.count)
+
class SingleTransactionModeTest(unittest.TestCase):
"""Ensure that filters are only run once on any given block of text when
@@ -103,18 +90,14 @@ def render(self, template_source):
foo = 'bar',
# No-op function, for use with #call
- call_noop = lambda body: body,
-
- # #call function that re-blesses its body
- call_rebless = lambda body: UniqueFilter.unfilter(body),
+ identity = lambda body: body,
)
template = Cheetah.Template.Template(
template_source,
filter=UniqueFilter,
searchList=[scope],
- compilerSettings=dict(
- autoAssignDummyTransactionToSelf=True),
+ compilerSettings=dict(autoAssignDummyTransactionToSelf=True),
)
return template.respond().strip()
@@ -126,35 +109,21 @@ def test_def(self):
$print_foo()
""")
- assert output == '@bar', (output, "should be @bar")
+
+ expected = '<1>bar</1>'
+ assert output == expected, "%r should be %r" % (output, expected)
def test_naive_call(self):
- try:
- # This will fail because $foo is substituted and filtered inside
- # the #call block, the function is run, and then the return value
- # (still containing $foo) is filtered again
- output = self.render("""
- #def print_foo: $foo
-
- #call $call_noop
- [$print_foo()]
- #end call
- """)
- except UniqueError:
- pass
- else:
- assert False, "UniqueFilter should have raised UniqueError"
-
- def test_fixed_call(self):
+ # This will be filtered twice because $foo is substituted and filtered
+ # inside the #call block, the function is run, and then the return
+ # value (still containing $foo) is filtered again
output = self.render("""
#def print_foo: $foo
- #call $call_rebless
- [$print_foo()]
- #end call
+ #call $identity # [$print_foo()] #end call
""")
-
- assert output == '@[bar]', (output, "should be @[bar]")
+ expected = '<2> [<1>bar</1>] </2>'
+ assert output == expected, "%r should be %r" % (output, expected)
if __name__ == '__main__':
unittest.main()
@@ -211,6 +211,7 @@ class EmptyTemplate(OutputTest):
def test1(self):
"""an empty string for the template"""
+ filters_copy = warnings.filters[:]
warnings.filterwarnings('error',
'You supplied an empty string for the source!',
UserWarning)
@@ -232,6 +233,9 @@ def test1(self):
self.verify("#implements respond(foo=1234)", "")
+ # Restore the old filters.
+ warnings.filters[:] = filters_copy
+
class Backslashes(OutputTest):
convertEOLs = False
@@ -2973,15 +2977,10 @@ def test2(self):
)
def test3(self):
- # Monkeypatch showwarning to do logging; this is actually what the docs
- # recommend!
- warnings_log = []
- def showwarning(message, category, filename, lineno, file=None, line=None):
- # message is actually a warning object when using warnings.warn()
- warnings_log.append(message.message)
- orig_showwarning = warnings.showwarning
- warnings.showwarning = showwarning
-
+ filters_copy = warnings.filters[:]
+ warnings.filterwarnings('error',
+ 'Ignoring buffer contents due to use of #return',
+ UserWarning)
try:
self.verify(
"#def foo\n"
@@ -2992,13 +2991,13 @@ def showwarning(message, category, filename, lineno, file=None, line=None):
"$buf $buf",
'output output'
)
+ except UserWarning:
+ pass
+ else:
+ self.fail("Expected warning about losing foo()'s contents")
- assert any(
- 'Ignoring buffer contents due to use of #return' in warning
- for warning in warnings_log
- ), "Expected warning about losing foo()'s contents"
- finally:
- warnings.showwarning = orig_showwarning
+ # Restore the old filters.
+ warnings.filters[:] = filters_copy

0 comments on commit 6e3e640

Please sign in to comment.