"Fossies" - the Fresh Open Source Software Archive

Member "cheetah3-3.2.6.post2/Cheetah/Tests/SyntaxAndOutput.py" (20 Apr 2021, 94010 Bytes) of package /linux/www/cheetah3-3.2.6.post2.tar.gz:


As a special service "Fossies" has tried to format the requested source page into HTML format using (guessed) Python source code syntax highlighting (style: standard) with prefixed line numbers. Alternatively you can here view or download the uninterpreted source code file. See also the last Fossies "Diffs" side-by-side code changes report for "SyntaxAndOutput.py": 3-3.2.5_vs_3-3.2.6.

    1 #!/usr/bin/env python
    2 # -*- coding: latin-1 -*-
    3 
    4 '''
    5 Syntax and Output tests.
    6 
    7 TODO
    8 - #finally
    9 - #filter
   10 - #errorCatcher
   11 - #echo
   12 - #silent
   13 '''
   14 
   15 
   16 ##################################################
   17 # DEPENDENCIES ##
   18 
   19 import os
   20 import os.path
   21 import sys
   22 import unittest
   23 import warnings
   24 
   25 from Cheetah.NameMapper import NotFound
   26 from Cheetah.Template import Template
   27 from Cheetah.Parser import ParseError
   28 from Cheetah.Compiler import DEFAULT_COMPILER_SETTINGS
   29 from Cheetah.compat import PY2
   30 
   31 
   32 class Unspecified(object):
   33     pass
   34 
   35 
   36 def testdecorator(func):
   37     return func
   38 
   39 
   40 class DummyClass:
   41     _called = False
   42 
   43     def __str__(self):
   44         return 'object'
   45 
   46     def meth(self, arg="arff"):
   47         return str(arg)
   48 
   49     def meth1(self, arg="doo"):
   50         return arg
   51 
   52     def meth2(self, arg1="a1", arg2="a2"):
   53         return str(arg1) + str(arg2)
   54 
   55     def methWithPercentSignDefaultArg(self, arg1="110%"):
   56         return str(arg1)
   57 
   58     def callIt(self, arg=1234):
   59         self._called = True
   60         self._callArg = arg
   61 
   62 
   63 def dummyFunc(arg="Scooby"):
   64     return arg
   65 
   66 
   67 defaultTestNameSpace = {
   68     'aStr': 'blarg',
   69     'anInt': 1,
   70     'aFloat': 1.5,
   71     'aList': ['item0', 'item1', 'item2'],
   72     'aDict': {'one': 'item1',
   73               'two': 'item2',
   74               'nestedDict': {1: 'nestedItem1',
   75                              'two': 'nestedItem2'
   76                              },
   77               'nestedFunc': dummyFunc,
   78               },
   79     'aFunc': dummyFunc,
   80     'anObj': DummyClass(),
   81     'aMeth': DummyClass().meth1,
   82     'aStrToBeIncluded': "$aStr $anInt",
   83     'none': None,
   84     'emptyString': '',
   85     'numOne': 1,
   86     'numTwo': 2,
   87     'zero': 0,
   88     'tenDigits': 1234567890,
   89     'webSafeTest': 'abc <=> &',
   90     'strip1': '  \t   strippable whitespace   \t\t  \n',
   91     'strip2': '  \t   strippable whitespace   \t\t  ',
   92     'strip3': '  \t   strippable whitespace   \t\t\n1 2  3\n',
   93 
   94     'blockToBeParsed': """$numOne $numTwo""",
   95     'includeBlock2': """$numOne $numTwo $aSetVar""",
   96 
   97     'includeFileName': 'parseTest.txt',
   98     'listOfLambdas': [lambda x: x, lambda x: x, lambda x: x],
   99     'list': [
  100         {'index': 0, 'numOne': 1, 'numTwo': 2},
  101         {'index': 1, 'numOne': 1, 'numTwo': 2},
  102     ],
  103     'nameList': [('john', 'doe'), ('jane', 'smith')],
  104     'letterList': ['a', 'b', 'c'],
  105     '_': lambda x: 'Translated: ' + x,
  106     'unicodeData': u'aoeu12345\u1234',
  107 }
  108 
  109 
  110 ##################################################
  111 # TEST BASE CLASSES
  112 
  113 class OutputTest(unittest.TestCase):
  114     report = '''
  115 Template output mismatch:
  116 
  117     Input Template =
  118 %(template)s%(end)s
  119 
  120     Expected Output =
  121 %(expected)s%(end)s
  122 
  123     Actual Output =
  124 %(actual)s%(end)s'''
  125 
  126     convertEOLs = True
  127     _EOLreplacement = None
  128     _debugEOLReplacement = False
  129 
  130     DEBUGLEV = 0
  131     _searchList = [defaultTestNameSpace]
  132 
  133     _useNewStyleCompilation = True
  134     # _useNewStyleCompilation = False
  135 
  136     _extraCompileKwArgs = None
  137 
  138     def searchList(self):
  139         return self._searchList
  140 
  141     def verify(self, input, expectedOutput,
  142                inputEncoding=None,
  143                outputEncoding=None,
  144                convertEOLs=Unspecified):
  145         if self._EOLreplacement:
  146             if convertEOLs is Unspecified:
  147                 convertEOLs = self.convertEOLs
  148             if convertEOLs:
  149                 input = input.replace('\n', self._EOLreplacement)
  150                 expectedOutput = expectedOutput.replace(
  151                     '\n', self._EOLreplacement)
  152 
  153         self._input = input
  154         if self._useNewStyleCompilation:
  155             extraKwArgs = self._extraCompileKwArgs or {}
  156 
  157             templateClass = Template.compile(
  158                 source=input,
  159                 compilerSettings=self._getCompilerSettings(),
  160                 keepRefToGeneratedCode=True,
  161                 **extraKwArgs
  162             )
  163             moduleCode = templateClass._CHEETAH_generatedModuleCode
  164             searchList = self.searchList() or self._searchList
  165             self.template = templateObj = templateClass(searchList=searchList)
  166         else:
  167             self.template = templateObj = Template(
  168                 input,
  169                 searchList=self.searchList(),
  170                 compilerSettings=self._getCompilerSettings(),
  171             )
  172             moduleCode = templateObj._CHEETAH_generatedModuleCode
  173         if self.DEBUGLEV >= 1:
  174             print("Module: %s" % templateObj.__module__)
  175             print(
  176                 moduleCode.encode('ascii', 'backslashreplace').decode('ascii'))
  177         try:
  178             # rather than __str__, because of unicode
  179             output = templateObj.respond()
  180             assert output == expectedOutput, \
  181                 self._outputMismatchReport(output, expectedOutput)
  182         finally:
  183             templateObj.shutdown()
  184 
  185     def _getCompilerSettings(self):
  186         return {}
  187 
  188     def _outputMismatchReport(self, output, expectedOutput):
  189         if self._debugEOLReplacement and self._EOLreplacement:
  190             EOLrepl = self._EOLreplacement
  191             marker = '*EOL*'
  192             return self.report % {
  193                 'template': self._input.replace(EOLrepl, marker),
  194                 'expected': expectedOutput.replace(EOLrepl, marker),
  195                 'actual': output.replace(EOLrepl, marker),
  196                 'end': '(end)',
  197             }
  198         else:
  199             return self.report % {'template': self._input,
  200                                   'expected': expectedOutput,
  201                                   'actual': output,
  202                                   'end': '(end)'}
  203 
  204     def genClassCode(self):
  205         if hasattr(self, 'template'):
  206             return self.template.generatedClassCode()
  207 
  208     def genModuleCode(self):
  209         if hasattr(self, 'template'):
  210             return self.template.generatedModuleCode()
  211 
  212 ##################################################
  213 # TEST CASE CLASSES
  214 
  215 
  216 class EmptyTemplate(OutputTest):
  217     convertEOLs = False
  218 
  219     def test1(self):
  220         """an empty string for the template"""
  221 
  222         warnings.filterwarnings('error',
  223                                 'You supplied an empty string for the source!',
  224                                 UserWarning)
  225         try:
  226             self.verify("", "")
  227         except UserWarning:
  228             pass
  229         else:
  230             self.fail("Should warn about empty source strings.")
  231 
  232         try:
  233             self.verify("#implements foo", "")
  234         except NotImplementedError:
  235             pass
  236         else:
  237             self.fail(
  238                 "This should barf about respond() not being implemented.")
  239 
  240         self.verify("#implements respond", "")
  241 
  242         self.verify("#implements respond(foo=1234)", "")
  243 
  244 
  245 class Backslashes(OutputTest):
  246     convertEOLs = False
  247 
  248     def setUp(self):
  249         fp = open('backslashes.txt', 'w')
  250         fp.write(
  251             r'\ #LogFormat "%h %l %u %t \"%r\" %>s %b"' + '\n\n\n\n\n\n\n')
  252         fp.flush()
  253         fp.close()
  254 
  255     def tearDown(self):
  256         if os.path.exists('backslashes.txt'):
  257             os.remove('backslashes.txt')
  258 
  259     def test1(self):
  260         """ a single \\ using rawstrings"""
  261         self.verify(r"\ ",
  262                     r"\ ")
  263 
  264     def test2(self):
  265         """ a single \\ using rawstrings and lots of lines"""
  266         self.verify(r"\ " + "\n\n\n\n\n\n\n\n\n",
  267                     r"\ " + "\n\n\n\n\n\n\n\n\n")
  268 
  269     def test3(self):
  270         """ a single \\ without using rawstrings"""
  271         self.verify("\ \ ",
  272                     "\ \ ")
  273 
  274     def test4(self):
  275         """ single line from an apache conf file"""
  276         self.verify(r'#LogFormat "%h %l %u %t \"%r\" %>s %b"',
  277                     r'#LogFormat "%h %l %u %t \"%r\" %>s %b"')
  278 
  279     def test5(self):
  280         """ single line from an apache conf file with many NEWLINES
  281 
  282         The NEWLINES are used to make sure that MethodCompiler.commitStrConst()
  283         is handling long and short strings in the same fashion.  It uses
  284         triple-quotes for strings with lots of \\n in them and repr(theStr) for
  285         shorter strings with only a few newlines."""
  286 
  287         self.verify(
  288             r'#LogFormat "%h %l %u %t \"%r\" %>s %b"' + '\n\n\n\n\n\n\n',
  289             r'#LogFormat "%h %l %u %t \"%r\" %>s %b"' + '\n\n\n\n\n\n\n')
  290 
  291     def test6(self):
  292         """ test backslash handling in an included file"""
  293         self.verify(
  294             r'#include "backslashes.txt"',
  295             r'\ #LogFormat "%h %l %u %t \"%r\" %>s %b"' + '\n\n\n\n\n\n\n')
  296 
  297     def test7(self):
  298         """ a single \\ without using rawstrings plus many NEWLINES"""
  299         self.verify("\ \ " + "\n\n\n\n\n\n\n\n\n",
  300                     "\ \ " + "\n\n\n\n\n\n\n\n\n")
  301 
  302     def test8(self):
  303         """ single line from an apache conf file with single quotes and many NEWLINES
  304         """
  305 
  306         self.verify(
  307             r"""#LogFormat '%h %l %u %t \"%r\" %>s %b'""" + '\n\n\n\n\n\n\n',
  308             r"""#LogFormat '%h %l %u %t \"%r\" %>s %b'""" + '\n\n\n\n\n\n\n')
  309 
  310 
  311 class NonTokens(OutputTest):
  312     def test1(self):
  313         """dollar signs not in Cheetah $vars"""
  314         self.verify("$ $$ $5 $. $ test",
  315                     "$ $$ $5 $. $ test")
  316 
  317     def test2(self):
  318         """hash not in #directives"""
  319         self.verify("# \# #5 ",
  320                     "# # #5 ")
  321 
  322     def test3(self):
  323         """escapted comments"""
  324         self.verify("  \##escaped comment  ",
  325                     "  ##escaped comment  ")
  326 
  327     def test4(self):
  328         """escapted multi-line comments"""
  329         self.verify("  \#*escaped comment \n*#  ",
  330                     "  #*escaped comment \n*#  ")
  331 
  332     def test5(self):
  333         """1 dollar sign"""
  334         self.verify("$",
  335                     "$")
  336 
  337     def _X_test6(self):
  338         """1 dollar sign followed by hash"""
  339         self.verify("\n$#\n",
  340                     "\n$#\n")
  341 
  342     def test6(self):
  343         """1 dollar sign followed by EOL Slurp Token"""
  344         if DEFAULT_COMPILER_SETTINGS['EOLSlurpToken']:
  345             self.verify("\n$%s\n" % DEFAULT_COMPILER_SETTINGS['EOLSlurpToken'],
  346                         "\n$")
  347         else:
  348             self.verify("\n$#\n",
  349                         "\n$#\n")
  350 
  351 
  352 class Comments_SingleLine(OutputTest):
  353     def test1(self):
  354         """## followed by WS"""
  355         self.verify("##    ",
  356                     "")
  357 
  358     def test2(self):
  359         """## followed by NEWLINE"""
  360         self.verify("##\n",
  361                     "")
  362 
  363     def test3(self):
  364         """## followed by text then NEWLINE"""
  365         self.verify("## oeuao aoe uaoe \n",
  366                     "")
  367 
  368     def test4(self):
  369         """## gobbles leading WS"""
  370         self.verify("    ## oeuao aoe uaoe \n",
  371                     "")
  372 
  373     def test5(self):
  374         """## followed by text then NEWLINE, + leading WS"""
  375         self.verify("    ## oeuao aoe uaoe \n",
  376                     "")
  377 
  378     def test6(self):
  379         """## followed by EOF"""
  380         self.verify("##",
  381                     "")
  382 
  383     def test7(self):
  384         """## followed by EOF with leading WS"""
  385         self.verify("    ##",
  386                     "")
  387 
  388     def test8(self):
  389         """## gobble line
  390         with text on previous and following lines"""
  391         self.verify("line1\n   ## aoeu 1234   \nline2",
  392                     "line1\nline2")
  393 
  394     def test9(self):
  395         """## don't gobble line
  396         with text on previous and following lines"""
  397         self.verify("line1\n 12 ## aoeu 1234   \nline2",
  398                     "line1\n 12 \nline2")
  399 
  400     def test10(self):
  401         """## containing $placeholders
  402         """
  403         self.verify("##$a$b $c($d)",
  404                     "")
  405 
  406     def test11(self):
  407         """## containing #for directive
  408         """
  409         self.verify("##for $i in range(15)",
  410                     "")
  411 
  412 
  413 class Comments_MultiLine_NoGobble(OutputTest):
  414     """Multiline comments used to not gobble whitespace
  415 
  416     They do now, but this can be turned off with a compilerSetting.
  417     """
  418     def _getCompilerSettings(self):
  419         return {'gobbleWhitespaceAroundMultiLineComments': False}
  420 
  421     def test1(self):
  422         """#* *# followed by WS
  423         Shouldn't gobble WS
  424         """
  425         self.verify("#* blarg *#   ",
  426                     "   ")
  427 
  428     def test2(self):
  429         """#* *# preceded and followed by WS
  430         Shouldn't gobble WS
  431         """
  432         self.verify("   #* blarg *#   ",
  433                     "      ")
  434 
  435     def test3(self):
  436         """#* *# followed by WS, with NEWLINE
  437         Shouldn't gobble WS
  438         """
  439         self.verify("#* \nblarg\n *#   ",
  440                     "   ")
  441 
  442     def test4(self):
  443         """#* *# preceded and followed by WS, with NEWLINE
  444         Shouldn't gobble WS
  445         """
  446         self.verify("   #* \nblarg\n *#   ",
  447                     "      ")
  448 
  449 
  450 class Comments_MultiLine(OutputTest):
  451     """
  452     Note: Multiline comments don't gobble whitespace!
  453     """
  454 
  455     def test1(self):
  456         """#* *# followed by WS
  457         Should gobble WS
  458         """
  459         self.verify("#* blarg *#   ",
  460                     "")
  461 
  462     def test2(self):
  463         """#* *# preceded and followed by WS
  464         Should gobble WS
  465         """
  466         self.verify("   #* blarg *#   ",
  467                     "")
  468 
  469     def test3(self):
  470         """#* *# followed by WS, with NEWLINE
  471         Shouldn't gobble WS
  472         """
  473         self.verify("#* \nblarg\n *#   ",
  474                     "")
  475 
  476     def test4(self):
  477         """#* *# preceded and followed by WS, with NEWLINE
  478         Shouldn't gobble WS
  479         """
  480         self.verify("   #* \nblarg\n *#   ",
  481                     "")
  482 
  483     def test5(self):
  484         """#* *# containing nothing
  485         """
  486         self.verify("#**#",
  487                     "")
  488 
  489     def test6(self):
  490         """#* *# containing only NEWLINES
  491         """
  492         self.verify("  #*\n\n\n\n\n\n\n\n*#  ",
  493                     "")
  494 
  495     def test7(self):
  496         """#* *# containing $placeholders
  497         """
  498         self.verify("#* $var $var(1234*$c) *#",
  499                     "")
  500 
  501     def test8(self):
  502         """#* *# containing #for directive
  503         """
  504         self.verify("#* #for $i in range(15) *#",
  505                     "")
  506 
  507     def test9(self):
  508         """ text around #* *# containing #for directive
  509         """
  510         self.verify("foo\nfoo bar #* #for $i in range(15) *# foo\n",
  511                     "foo\nfoo bar  foo\n")
  512 
  513     def test10(self):
  514         """ text around #* *# containing #for directive and trailing whitespace
  515         which should be gobbled
  516         """
  517         self.verify("foo\nfoo bar #* #for $i in range(15) *#   \ntest",
  518                     "foo\nfoo bar \ntest")
  519 
  520     def test11(self):
  521         """
  522         Text around #* *# containing #for directive and newlines:
  523         trailing whitespace which should be gobbled.
  524         """
  525         self.verify("foo\nfoo bar #* \n\n#for $i in range(15) \n\n*#   \ntest",
  526                     "foo\nfoo bar \ntest")
  527 
  528 
  529 class Placeholders(OutputTest):
  530     def test1(self):
  531         """1 placeholder"""
  532         self.verify("$aStr", "blarg")
  533 
  534     def test2(self):
  535         """2 placeholders"""
  536         self.verify("$aStr $anInt", "blarg 1")
  537 
  538     def test3(self):
  539         """2 placeholders, back-to-back"""
  540         self.verify("$aStr$anInt", "blarg1")
  541 
  542     def test4(self):
  543         """1 placeholder enclosed in ()"""
  544         self.verify("$(aStr)", "blarg")
  545 
  546     def test5(self):
  547         """1 placeholder enclosed in {}"""
  548         self.verify("${aStr}", "blarg")
  549 
  550     def test6(self):
  551         """1 placeholder enclosed in []"""
  552         self.verify("$[aStr]", "blarg")
  553 
  554     def test7(self):
  555         """1 placeholder enclosed in () + WS
  556 
  557         Test to make sure that $(<WS><identifier>.. matches
  558         """
  559         self.verify("$( aStr   )", "blarg")
  560 
  561     def test8(self):
  562         """1 placeholder enclosed in {} + WS"""
  563         self.verify("${ aStr   }", "blarg")
  564 
  565     def test9(self):
  566         """1 placeholder enclosed in [] + WS"""
  567         self.verify("$[ aStr   ]", "blarg")
  568 
  569     def test10(self):
  570         """1 placeholder enclosed in () + WS + * cache
  571 
  572         Test to make sure that $*(<WS><identifier>.. matches
  573         """
  574         self.verify("$*( aStr   )", "blarg")
  575 
  576     def test11(self):
  577         """1 placeholder enclosed in {} + WS + *cache"""
  578         self.verify("$*{ aStr   }", "blarg")
  579 
  580     def test12(self):
  581         """1 placeholder enclosed in [] + WS + *cache"""
  582         self.verify("$*[ aStr   ]", "blarg")
  583 
  584     def test13(self):
  585         """1 placeholder enclosed in {} + WS + *<int>*cache"""
  586         self.verify("$*5*{ aStr   }", "blarg")
  587 
  588     def test14(self):
  589         """1 placeholder enclosed in [] + WS + *<int>*cache"""
  590         self.verify("$*5*[ aStr   ]", "blarg")
  591 
  592     def test15(self):
  593         """1 placeholder enclosed in {} + WS + *<float>*cache"""
  594         self.verify("$*0.5d*{ aStr   }", "blarg")
  595 
  596     def test16(self):
  597         """1 placeholder enclosed in [] + WS + *<float>*cache"""
  598         self.verify("$*.5*[ aStr   ]", "blarg")
  599 
  600     def test17(self):
  601         """1 placeholder + *<int>*cache"""
  602         self.verify("$*5*aStr", "blarg")
  603 
  604     def test18(self):
  605         """1 placeholder *<float>*cache"""
  606         self.verify("$*0.5h*aStr", "blarg")
  607 
  608     def test19(self):
  609         """1 placeholder surrounded by single quotes and multiple newlines"""
  610         self.verify("""'\n\n\n\n'$aStr'\n\n\n\n'""",
  611                     """'\n\n\n\n'blarg'\n\n\n\n'""")
  612 
  613     def test20(self):
  614         """silent mode $!placeholders """
  615         self.verify(
  616             "$!aStr$!nonExistant$!*nonExistant$!{nonExistant}", "blarg")
  617 
  618         try:
  619             self.verify("$!aStr$nonExistant", "blarg")
  620         except NotFound:
  621             pass
  622         else:
  623             self.fail('should raise NotFound exception')
  624 
  625     def test21(self):
  626         """Make sure that $*caching is actually working"""
  627         namesStr = 'You Me Them Everyone'
  628         names = namesStr.split()
  629 
  630         tmpl = Template.compile('#for name in $names: $name ', baseclass=dict)
  631         assert str(tmpl({'names': names})).strip() == namesStr
  632 
  633         tmpl = tmpl.subclass('#for name in $names: $*name ')
  634         assert str(tmpl({'names': names})) == 'You ' * len(names)
  635 
  636         tmpl = tmpl.subclass('#for name in $names: $*1*name ')
  637         assert str(tmpl({'names': names})) == 'You ' * len(names)
  638 
  639         tmpl = tmpl.subclass('#for name in $names: $*1*(name) ')
  640         assert str(tmpl({'names': names})) == 'You ' * len(names)
  641 
  642         tmpl = tmpl.subclass('#for name in $names: $*1*(name) ')
  643         assert str(tmpl(names=names)) == 'You ' * len(names)
  644 
  645 
  646 class Placeholders_Vals(OutputTest):
  647     convertEOLs = False
  648 
  649     def test1(self):
  650         """string"""
  651         self.verify("$aStr", "blarg")
  652 
  653     def test2(self):
  654         """string - with whitespace"""
  655         self.verify(" $aStr ", " blarg ")
  656 
  657     def test3(self):
  658         """empty string - with whitespace"""
  659         self.verify("$emptyString", "")
  660 
  661     def test4(self):
  662         """int"""
  663         self.verify("$anInt", "1")
  664 
  665     def test5(self):
  666         """float"""
  667         self.verify("$aFloat", "1.5")
  668 
  669     def test6(self):
  670         """list"""
  671         self.verify("$aList", "['item0', 'item1', 'item2']")
  672 
  673     def test7(self):
  674         """None
  675 
  676         The default output filter is ReplaceNone.
  677         """
  678         self.verify("$none", "")
  679 
  680     def test8(self):
  681         """True, False
  682         """
  683         self.verify("$True $False", "%s %s" % (repr(True), repr(False)))
  684 
  685     def test9(self):
  686         """$_
  687         """
  688         self.verify("$_('foo')", "Translated: foo")
  689 
  690 
  691 class PlaceholderStrings(OutputTest):
  692     def test1(self):
  693         """some c'text $placeholder text' strings"""
  694         self.verify("$str(c'$aStr')", "blarg")
  695 
  696     def test2(self):
  697         """some c'text $placeholder text' strings"""
  698         self.verify("$str(c'$aStr.upper')", "BLARG")
  699 
  700     def test3(self):
  701         """some c'text $placeholder text' strings"""
  702         self.verify(
  703             "$str(c'$(aStr.upper.replace(c\"A$str()\",\"\"))')", "BLRG")
  704 
  705     def test4(self):
  706         """some c'text $placeholder text' strings"""
  707         self.verify("#echo $str(c'$(aStr.upper)')", "BLARG")
  708 
  709     def test5(self):
  710         """some c'text $placeholder text' strings"""
  711         self.verify("#if 1 then $str(c'$(aStr.upper)') else 0", "BLARG")
  712 
  713     def test6(self):
  714         """some c'text $placeholder text' strings"""
  715         self.verify(
  716             "#if 1\n$str(c'$(aStr.upper)')#slurp\n#else\n0#end if", "BLARG")
  717 
  718     def test7(self):
  719         """some c'text $placeholder text' strings"""
  720         self.verify("#def foo(arg=c'$(\"BLARG\")')\n"
  721                     "$arg#slurp\n"
  722                     "#end def\n"
  723                     "$foo()$foo(c'$anInt')#slurp",
  724 
  725                     "BLARG1")
  726 
  727 
  728 class UnicodeStrings(OutputTest):
  729     def test1(self):
  730         """unicode data in placeholder
  731         """
  732         # self.verify(u"$unicodeData", defaultTestNameSpace['unicodeData'],
  733         #             outputEncoding='utf8')
  734         self.verify(u"$unicodeData", defaultTestNameSpace['unicodeData'])
  735 
  736     def test2(self):
  737         """unicode data in body
  738         """
  739         self.verify(u"aoeu12345\u1234", u"aoeu12345\u1234")
  740         # self.verify(u"#encoding utf8#aoeu12345\u1234", u"aoeu12345\u1234")
  741 
  742 
  743 class EncodingDirective(OutputTest):
  744     def test1(self):
  745         """basic #encoding """
  746         self.verify("#encoding utf-8\n1234",
  747                     "1234")
  748 
  749     def test2(self):
  750         """basic #encoding """
  751         self.verify("#encoding ascii\n1234",
  752                     "1234")
  753 
  754     def test3(self):
  755         """basic #encoding """
  756         source = b"#encoding utf-8\n\xe1\x88\xb4"
  757         if not PY2:
  758             source = source.decode('utf-8')
  759         self.verify(source,
  760                     u'\u1234', outputEncoding='utf8')
  761 
  762     def test4(self):
  763         """basic #encoding """
  764         source = b"#encoding latin-1\n\xe1\x88\xb4"
  765         if not PY2:
  766             source = source.decode('latin-1')
  767         self.verify(source,
  768                     u"\xe1\x88\xb4")
  769 
  770     def test5(self):
  771         """basic #encoding """
  772         self.verify("#encoding latin-1\nAndr\202",
  773                     u'Andr\202')
  774 
  775     def test6(self):
  776         '''Using #encoding on the second line'''
  777         source = b"""### Comments on the first line
  778 #encoding utf-8\n\xe1\x88\xb4"""
  779         if not PY2:
  780             source = source.decode('utf-8')
  781         self.verify(source,
  782                     u'\u1234', outputEncoding='utf8')
  783 
  784 
  785 class UnicodeDirective(OutputTest):
  786     def test1(self):
  787         """basic #unicode """
  788         self.verify("#unicode utf-8\n1234",
  789                     u"1234")
  790 
  791         self.verify("#unicode ascii\n1234",
  792                     u"1234")
  793 
  794         self.verify("#unicode latin-1\n1234",
  795                     u"1234")
  796 
  797         self.verify("#unicode latin-1\n1234",
  798                     u"1234")
  799         self.verify("#unicode: latin-1\n1234",
  800                     u"1234")
  801         self.verify("#  unicode  : latin-1\n1234",
  802                     u"1234")
  803 
  804         self.verify(u"#unicode latin-1\n1234",
  805                     u"1234")
  806 
  807         self.verify("#encoding latin-1\n1234",
  808                     u"1234")
  809 
  810 
  811 class Placeholders_Esc(OutputTest):
  812     convertEOLs = False
  813 
  814     def test1(self):
  815         """1 escaped placeholder"""
  816         self.verify("\$var",
  817                     "$var")
  818 
  819     def test2(self):
  820         """2 escaped placeholders"""
  821         self.verify("\$var \$_",
  822                     "$var $_")
  823 
  824     def test3(self):
  825         """2 escaped placeholders - back to back"""
  826         self.verify("\$var\$_",
  827                     "$var$_")
  828 
  829     def test4(self):
  830         """2 escaped placeholders - nested"""
  831         self.verify("\$var(\$_)",
  832                     "$var($_)")
  833 
  834     def test5(self):
  835         """2 escaped placeholders - nested and enclosed"""
  836         self.verify("\$(var(\$_)",
  837                     "$(var($_)")
  838 
  839 
  840 class Placeholders_Calls(OutputTest):
  841     def test1(self):
  842         """func placeholder - no ()"""
  843         self.verify("$aFunc",
  844                     "Scooby")
  845 
  846     def test2(self):
  847         """func placeholder - with ()"""
  848         self.verify("$aFunc()",
  849                     "Scooby")
  850 
  851     def test3(self):
  852         r"""func placeholder - with (\n\n)"""
  853         self.verify("$aFunc(\n\n)",
  854                     "Scooby", convertEOLs=False)
  855 
  856     def test4(self):
  857         r"""func placeholder - with (\n\n) and $() enclosure"""
  858         self.verify("$(aFunc(\n\n))",
  859                     "Scooby", convertEOLs=False)
  860 
  861     def test5(self):
  862         r"""func placeholder - with (\n\n) and ${} enclosure"""
  863         self.verify("${aFunc(\n\n)}",
  864                     "Scooby", convertEOLs=False)
  865 
  866     def test6(self):
  867         """func placeholder - with (int)"""
  868         self.verify("$aFunc(1234)",
  869                     "1234")
  870 
  871     def test7(self):
  872         r"""func placeholder - with (\nint\n)"""
  873         self.verify("$aFunc(\n1234\n)",
  874                     "1234", convertEOLs=False)
  875 
  876     def test8(self):
  877         """func placeholder - with (string)"""
  878         self.verify("$aFunc('aoeu')",
  879                     "aoeu")
  880 
  881     def test9(self):
  882         """func placeholder - with ('''string''')"""
  883         self.verify("$aFunc('''aoeu''')",
  884                     "aoeu")
  885 
  886     def test10(self):
  887         r"""func placeholder - with ('''\nstring\n''')"""
  888         self.verify("$aFunc('''\naoeu\n''')",
  889                     "\naoeu\n", convertEOLs=False)
  890 
  891     def test11(self):
  892         r"""func placeholder - with ('''\nstring'\n''')"""
  893         self.verify("$aFunc('''\naoeu'\n''')",
  894                     "\naoeu'\n", convertEOLs=False)
  895 
  896     def test12(self):
  897         r'''func placeholder - with ("""\nstring\n""")'''
  898         self.verify('$aFunc("""\naoeu\n""")',
  899                     "\naoeu\n", convertEOLs=False)
  900 
  901     def test13(self):
  902         """func placeholder - with (string*int)"""
  903         self.verify("$aFunc('aoeu'*2)",
  904                     "aoeuaoeu")
  905 
  906     def test14(self):
  907         """func placeholder - with (int*int)"""
  908         self.verify("$aFunc(2*2)",
  909                     "4")
  910 
  911     def test15(self):
  912         """func placeholder - with (int*float)"""
  913         self.verify("$aFunc(2*2.0)",
  914                     "4.0")
  915 
  916     def test16(self):
  917         r"""func placeholder - with (int\n*\nfloat)"""
  918         self.verify("$aFunc(2\n*\n2.0)",
  919                     "4.0", convertEOLs=False)
  920 
  921     def test17(self):
  922         """func placeholder - with ($arg=float)"""
  923         self.verify("$aFunc($arg=4.0)",
  924                     "4.0")
  925 
  926     def test18(self):
  927         """func placeholder - with (arg=float)"""
  928         self.verify("$aFunc(arg=4.0)",
  929                     "4.0")
  930 
  931     def test19(self):
  932         """deeply nested argstring, no enclosure"""
  933         self.verify("$aFunc($arg=$aMeth($arg=$aFunc(1)))",
  934                     "1")
  935 
  936     def test20(self):
  937         """deeply nested argstring, no enclosure + with WS"""
  938         self.verify("$aFunc(  $arg = $aMeth( $arg = $aFunc( 1 ) ) )",
  939                     "1")
  940 
  941     def test21(self):
  942         """deeply nested argstring, () enclosure + with WS"""
  943         self.verify("$(aFunc(  $arg = $aMeth( $arg = $aFunc( 1 ) ) ) )",
  944                     "1")
  945 
  946     def test22(self):
  947         """deeply nested argstring, {} enclosure + with WS"""
  948         self.verify("${aFunc(  $arg = $aMeth( $arg = $aFunc( 1 ) ) ) }",
  949                     "1")
  950 
  951     def test23(self):
  952         """deeply nested argstring, [] enclosure + with WS"""
  953         self.verify("$[aFunc(  $arg = $aMeth( $arg = $aFunc( 1 ) ) ) ]",
  954                     "1")
  955 
  956     def test24(self):
  957         """deeply nested argstring, () enclosure + *cache"""
  958         self.verify("$*(aFunc(  $arg = $aMeth( $arg = $aFunc( 1 ) ) ) )",
  959                     "1")
  960 
  961     def test25(self):
  962         """deeply nested argstring, () enclosure + *15*cache"""
  963         self.verify("$*15*(aFunc(  $arg = $aMeth( $arg = $aFunc( 1 ) ) ) )",
  964                     "1")
  965 
  966     def test26(self):
  967         """a function call with the Python None kw."""
  968         self.verify("$aFunc(None)",
  969                     "")
  970 
  971 
  972 class NameMapper(OutputTest):
  973     def test1(self):
  974         """autocalling"""
  975         self.verify("$aFunc! $aFunc().",
  976                     "Scooby! Scooby.")
  977 
  978     def test2(self):
  979         """nested autocalling"""
  980         self.verify("$aFunc($aFunc).",
  981                     "Scooby.")
  982 
  983     def test3(self):
  984         """list subscription"""
  985         self.verify("$aList[0]",
  986                     "item0")
  987 
  988     def test4(self):
  989         """list slicing"""
  990         self.verify("$aList[:2]",
  991                     "['item0', 'item1']")
  992 
  993     def test5(self):
  994         """list slicing and subcription combined"""
  995         self.verify("$aList[:2][0]",
  996                     "item0")
  997 
  998     def test6(self):
  999         """dictionary access - NameMapper style"""
 1000         self.verify("$aDict.one",
 1001                     "item1")
 1002 
 1003     def test7(self):
 1004         """dictionary access - Python style"""
 1005         self.verify("$aDict['one']",
 1006                     "item1")
 1007 
 1008     def test8(self):
 1009         """dictionary access combined with autocalled string method"""
 1010         self.verify("$aDict.one.upper",
 1011                     "ITEM1")
 1012 
 1013     def test9(self):
 1014         """dictionary access combined with string method"""
 1015         self.verify("$aDict.one.upper()",
 1016                     "ITEM1")
 1017 
 1018     def test10(self):
 1019         """nested dictionary access - NameMapper style"""
 1020         self.verify("$aDict.nestedDict.two",
 1021                     "nestedItem2")
 1022 
 1023     def test11(self):
 1024         """nested dictionary access - Python style"""
 1025         self.verify("$aDict['nestedDict']['two']",
 1026                     "nestedItem2")
 1027 
 1028     def test12(self):
 1029         """nested dictionary access - alternating style"""
 1030         self.verify("$aDict['nestedDict'].two",
 1031                     "nestedItem2")
 1032 
 1033     def test13(self):
 1034         """nested dictionary access using method - alternating style"""
 1035         self.verify("$aDict.get('nestedDict').two",
 1036                     "nestedItem2")
 1037 
 1038     def test14(self):
 1039         """nested dictionary access - NameMapper style - followed by method"""
 1040         self.verify("$aDict.nestedDict.two.upper",
 1041                     "NESTEDITEM2")
 1042 
 1043     def test15(self):
 1044         """nested dictionary access - alternating style - followed by method"""
 1045         self.verify("$aDict['nestedDict'].two.upper",
 1046                     "NESTEDITEM2")
 1047 
 1048     def test16(self):
 1049         """
 1050         Nested dictionary access - NameMapper style - followed by method,
 1051         then slice.
 1052         """
 1053         self.verify("$aDict.nestedDict.two.upper[:4]",
 1054                     "NEST")
 1055 
 1056     def test17(self):
 1057         """nested dictionary access - Python style using a soft-coded key"""
 1058         self.verify("$aDict[$anObj.meth('nestedDict')].two",
 1059                     "nestedItem2")
 1060 
 1061     def test18(self):
 1062         """object method access"""
 1063         self.verify("$anObj.meth1",
 1064                     "doo")
 1065 
 1066     def test19(self):
 1067         """object method access, followed by complex slice"""
 1068         self.verify("$anObj.meth1[0: ((4//4*2)*2)//$anObj.meth1(2) ]",
 1069                     "do")
 1070 
 1071     def test20(self):
 1072         """object method access, followed by a very complex slice
 1073         If it can pass this one, it's safe to say it works!!"""
 1074         self.verify(
 1075             "$( anObj.meth1[0:\n (\n(4//4*2)*2)//$anObj.meth1(2)\n ] )",
 1076             "do")
 1077 
 1078     def test21(self):
 1079         """object method access with % in the default arg for the meth.
 1080 
 1081         This tests a bug that Jeff Johnson found and submitted a patch to SF
 1082         for."""
 1083 
 1084         self.verify("$anObj.methWithPercentSignDefaultArg",
 1085                     "110%")
 1086 
 1087 
 1088 # class NameMapperDict(OutputTest):
 1089 #
 1090 #    _searchList = [{"update": "Yabba dabba doo!"}]
 1091 #
 1092 #    def test1(self):
 1093 #        if NameMapper_C_VERSION:
 1094 #            return # This feature is not in the C version yet.
 1095 #        self.verify("$update", "Yabba dabba doo!")
 1096 #
 1097 
 1098 class CacheDirective(OutputTest):
 1099 
 1100     def test1(self):
 1101         r"""simple #cache """
 1102         self.verify("#cache:$anInt",
 1103                     "1")
 1104 
 1105     def test2(self):
 1106         r"""simple #cache + WS"""
 1107         self.verify("  #cache  \n$anInt#end cache",
 1108                     "1")
 1109 
 1110     def test3(self):
 1111         r"""simple #cache ... #end cache"""
 1112         self.verify("""#cache id='cache1', timer=150m
 1113 $anInt
 1114 #end cache
 1115 $aStr""",
 1116                     "1\nblarg")
 1117 
 1118     def test4(self):
 1119         r"""2 #cache ... #end cache blocks"""
 1120         self.verify("""#slurp
 1121 #def foo
 1122 #cache ID='cache1', timer=150m
 1123 $anInt
 1124 #end cache
 1125 #cache id='cache2', timer=15s
 1126  #for $i in range(5)
 1127 $i#slurp
 1128  #end for
 1129 #end cache
 1130 $aStr#slurp
 1131 #end def
 1132 $foo$foo$foo$foo$foo""",
 1133                     "1\n01234blarg"*5)  # noqa: E226,E501 missing whitespace around operator
 1134 
 1135     def test5(self):
 1136         r"""nested #cache blocks"""
 1137         self.verify("""#slurp
 1138 #def foo
 1139 #cache ID='cache1', timer=150m
 1140 $anInt
 1141 #cache id='cache2', timer=15s
 1142  #for $i in range(5)
 1143 $i#slurp
 1144  #end for
 1145 $*(6)#slurp
 1146 #end cache
 1147 #end cache
 1148 $aStr#slurp
 1149 #end def
 1150 $foo$foo$foo$foo$foo""",
 1151                     "1\n012346blarg"*5)  # noqa: E226,E501 missing whitespace around operator
 1152 
 1153     def test6(self):
 1154         r"""Make sure that partial directives don't match"""
 1155         self.verify("#cache_foo",
 1156                     "#cache_foo")
 1157         self.verify("#cached",
 1158                     "#cached")
 1159 
 1160 
 1161 class CallDirective(OutputTest):
 1162 
 1163     def test1(self):
 1164         r"""simple #call """
 1165         self.verify("#call int\n$anInt#end call",
 1166                     "1")
 1167         # single line version
 1168         self.verify("#call int: $anInt",
 1169                     "1")
 1170         self.verify("#call int: 10\n$aStr",
 1171                     "10\nblarg")
 1172 
 1173     def test2(self):
 1174         r"""simple #call + WS"""
 1175         self.verify("#call int\n$anInt  #end call",
 1176                     "1")
 1177 
 1178     def test3(self):
 1179         r"""a longer #call"""
 1180         self.verify('''\
 1181 #def meth(arg)
 1182 $arg.upper()#slurp
 1183 #end def
 1184 #call $meth
 1185 $(1234+1) foo#slurp
 1186 #end call''',
 1187                     "1235 FOO")
 1188 
 1189     def test4(self):
 1190         r"""#call with keyword #args"""
 1191         self.verify('''\
 1192 #def meth(arg1, arg2)
 1193 $arg1.upper() - $arg2.lower()#slurp
 1194 #end def
 1195 #call self.meth
 1196 #arg arg1
 1197 $(1234+1) foo#slurp
 1198 #arg arg2
 1199 UPPER#slurp
 1200 #end call''',
 1201                     "1235 FOO - upper")
 1202 
 1203     def test5(self):
 1204         r"""#call with single-line keyword #args """
 1205         self.verify('''\
 1206 #def meth(arg1, arg2)
 1207 $arg1.upper() - $arg2.lower()#slurp
 1208 #end def
 1209 #call self.meth
 1210 #arg arg1:$(1234+1) foo#slurp
 1211 #arg arg2:UPPER#slurp
 1212 #end call''',
 1213                     "1235 FOO - upper")
 1214 
 1215     def test6(self):
 1216         """#call with python kwargs and cheetah output for the 1s positional
 1217         arg"""
 1218 
 1219         self.verify('''\
 1220 #def meth(arg1, arg2)
 1221 $arg1.upper() - $arg2.lower()#slurp
 1222 #end def
 1223 #call self.meth arg2="UPPER"
 1224 $(1234+1) foo#slurp
 1225 #end call''',
 1226                     "1235 FOO - upper")
 1227 
 1228     def test7(self):
 1229         """#call with python kwargs and #args"""
 1230         self.verify('''\
 1231 #def meth(arg1, arg2, arg3)
 1232 $arg1.upper() - $arg2.lower() - $arg3#slurp
 1233 #end def
 1234 #call self.meth arg2="UPPER", arg3=999
 1235 #arg arg1:$(1234+1) foo#slurp
 1236 #end call''',
 1237                     "1235 FOO - upper - 999")
 1238 
 1239     def test8(self):
 1240         """#call with python kwargs and #args, and using a function to get the
 1241         function that will be called"""
 1242         self.verify('''\
 1243 #def meth(arg1, arg2, arg3)
 1244 $arg1.upper() - $arg2.lower() - $arg3#slurp
 1245 #end def
 1246 #call getattr(self, "meth") arg2="UPPER", arg3=999
 1247 #arg arg1:$(1234+1) foo#slurp
 1248 #end call''',
 1249                     "1235 FOO - upper - 999")
 1250 
 1251     def test9(self):
 1252         """nested #call directives"""
 1253         self.verify('''\
 1254 #def meth(arg1)
 1255 $arg1#slurp
 1256 #end def
 1257 #def meth2(x,y)
 1258 $x$y#slurp
 1259 #end def
 1260 ##
 1261 #call self.meth
 1262 1#slurp
 1263 #call self.meth
 1264 2#slurp
 1265 #call self.meth
 1266 3#slurp
 1267 #end call 3
 1268 #set two = 2
 1269 #call self.meth2 y=c"$(10//$two)"
 1270 #arg x
 1271 4#slurp
 1272 #end call 4
 1273 #end call 2
 1274 #end call 1''',
 1275                     "12345")
 1276 
 1277 
 1278 class I18nDirective(OutputTest):
 1279     def test1(self):
 1280         r"""simple #call """
 1281         self.verify("#i18n \n$anInt#end i18n",
 1282                     "1")
 1283 
 1284         # single line version
 1285         self.verify("#i18n: $anInt",
 1286                     "1")
 1287         self.verify("#i18n: 10\n$aStr",
 1288                     "10\nblarg")
 1289 
 1290 
 1291 class CaptureDirective(OutputTest):
 1292     def test1(self):
 1293         r"""simple #capture"""
 1294         self.verify('''\
 1295 #capture cap1
 1296 $(1234+1) foo#slurp
 1297 #end capture
 1298 $cap1#slurp
 1299 ''',
 1300                     "1235 foo")
 1301 
 1302     def test2(self):
 1303         r"""slightly more complex #capture"""
 1304         self.verify('''\
 1305 #def meth(arg)
 1306 $arg.upper()#slurp
 1307 #end def
 1308 #capture cap1
 1309 $(1234+1) $anInt $meth("foo")#slurp
 1310 #end capture
 1311 $cap1#slurp
 1312 ''',
 1313                     "1235 1 FOO")
 1314 
 1315 
 1316 class SlurpDirective(OutputTest):
 1317     def test1(self):
 1318         r"""#slurp with 1 \n """
 1319         self.verify("#slurp\n",
 1320                     "")
 1321 
 1322     def test2(self):
 1323         r"""#slurp with 1 \n, leading whitespace
 1324         Should gobble"""
 1325         self.verify("       #slurp\n",
 1326                     "")
 1327 
 1328     def test3(self):
 1329         r"""#slurp with 1 \n, leading content
 1330         Shouldn't gobble"""
 1331         self.verify(" 1234 #slurp\n",
 1332                     " 1234 ")
 1333 
 1334     def test4(self):
 1335         r"""#slurp with WS then \n, leading content
 1336         Shouldn't gobble"""
 1337         self.verify(" 1234 #slurp    \n",
 1338                     " 1234 ")
 1339 
 1340     def test5(self):
 1341         r"""#slurp with garbage chars then \n, leading content
 1342         Should eat the garbage"""
 1343         self.verify(" 1234 #slurp garbage   \n",
 1344                     " 1234 ")
 1345 
 1346 
 1347 class EOLSlurpToken(OutputTest):
 1348     _EOLSlurpToken = DEFAULT_COMPILER_SETTINGS['EOLSlurpToken']
 1349 
 1350     def test1(self):
 1351         r"""#slurp with 1 \n """
 1352         self.verify("%s\n" % self._EOLSlurpToken,
 1353                     "")
 1354 
 1355     def test2(self):
 1356         r"""#slurp with 1 \n, leading whitespace
 1357         Should gobble"""
 1358         self.verify("       %s\n" % self._EOLSlurpToken,
 1359                     "")
 1360 
 1361     def test3(self):
 1362         r"""#slurp with 1 \n, leading content
 1363         Shouldn't gobble"""
 1364         self.verify(" 1234 %s\n" % self._EOLSlurpToken,
 1365                     " 1234 ")
 1366 
 1367     def test4(self):
 1368         r"""#slurp with WS then \n, leading content
 1369         Shouldn't gobble"""
 1370         self.verify(" 1234 %s    \n" % self._EOLSlurpToken,
 1371                     " 1234 ")
 1372 
 1373     def test5(self):
 1374         r"""#slurp with garbage chars then \n, leading content
 1375         Should NOT eat the garbage"""
 1376         self.verify(" 1234 %s garbage   \n" % self._EOLSlurpToken,
 1377                     " 1234 %s garbage   \n" % self._EOLSlurpToken)
 1378 
 1379 
 1380 if not DEFAULT_COMPILER_SETTINGS['EOLSlurpToken']:
 1381     del EOLSlurpToken
 1382 
 1383 
 1384 class RawDirective(OutputTest):
 1385     def test1(self):
 1386         """#raw till EOF"""
 1387         self.verify("#raw\n$aFunc().\n\n",
 1388                     "$aFunc().\n\n")
 1389 
 1390     def test2(self):
 1391         """#raw till #end raw"""
 1392         self.verify("#raw\n$aFunc().\n#end raw\n$anInt",
 1393                     "$aFunc().\n1")
 1394 
 1395     def test3(self):
 1396         """#raw till #end raw gobble WS"""
 1397         self.verify("  #raw  \n$aFunc().\n   #end raw  \n$anInt",
 1398                     "$aFunc().\n1")
 1399 
 1400     def test4(self):
 1401         """#raw till #end raw using explicit directive closure
 1402         Shouldn't gobble"""
 1403         self.verify("  #raw  #\n$aFunc().\n   #end raw  #\n$anInt",
 1404                     "  \n$aFunc().\n\n1")
 1405 
 1406     def test5(self):
 1407         """single-line short form #raw: """
 1408         self.verify("#raw: $aFunc().\n\n",
 1409                     "$aFunc().\n\n")
 1410 
 1411         self.verify("#raw: $aFunc().\n$anInt",
 1412                     "$aFunc().\n1")
 1413 
 1414     def test6(self):
 1415         """ Escape characters in a #raw block """
 1416         # noqa
 1417         self.verify("""\
 1418 #raw: This escape should be preserved: \\$unexpanded So should this one: \\#blah The string "\\012" should not disappear.""",  # noqa
 1419                     r"""This escape should be preserved: \$unexpanded So should this one: \#blah The string "\012" should not disappear.""")  # noqa
 1420 
 1421 
 1422 class BreakpointDirective(OutputTest):
 1423     def test1(self):
 1424         """#breakpoint part way through source code"""
 1425         self.verify("$aFunc(2).\n#breakpoint\n$anInt",
 1426                     "2.\n")
 1427 
 1428     def test2(self):
 1429         """#breakpoint at BOF"""
 1430         self.verify("#breakpoint\n$anInt",
 1431                     "")
 1432 
 1433     def test3(self):
 1434         """#breakpoint at EOF"""
 1435         self.verify("$anInt\n#breakpoint",
 1436                     "1\n")
 1437 
 1438 
 1439 class StopDirective(OutputTest):
 1440     def test1(self):
 1441         """#stop part way through source code"""
 1442         self.verify("$aFunc(2).\n#stop\n$anInt",
 1443                     "2.\n")
 1444 
 1445     def test2(self):
 1446         """#stop at BOF"""
 1447         self.verify("#stop\n$anInt",
 1448                     "")
 1449 
 1450     def test3(self):
 1451         """#stop at EOF"""
 1452         self.verify("$anInt\n#stop",
 1453                     "1\n")
 1454 
 1455     def test4(self):
 1456         """#stop in pos test block"""
 1457         self.verify("""\
 1458 $anInt
 1459 #if 1
 1460 inside the if block
 1461 #stop
 1462 #end if
 1463 blarg""",
 1464                     "1\ninside the if block\n")
 1465 
 1466     def test5(self):
 1467         """#stop in neg test block"""
 1468         self.verify("""$anInt
 1469 #if 0
 1470 inside the if block
 1471 #stop
 1472 #end if
 1473 blarg""",
 1474                     "1\nblarg")
 1475 
 1476 
 1477 class ReturnDirective(OutputTest):
 1478 
 1479     def test1(self):
 1480         """#return'ing an int """
 1481         self.verify("""1
 1482 $str($test-6)
 1483 3
 1484 #def test
 1485 #if 1
 1486 #return (3   *2)  \
 1487   + 2
 1488 #else
 1489 aoeuoaeu
 1490 #end if
 1491 #end def
 1492 """,
 1493                     "1\n2\n3\n")
 1494 
 1495     def test2(self):
 1496         """#return'ing an string """
 1497         self.verify("""1
 1498 $str($test[1])
 1499 3
 1500 #def test
 1501 #if 1
 1502 #return '123'
 1503 #else
 1504 aoeuoaeu
 1505 #end if
 1506 #end def
 1507 """,
 1508                     "1\n2\n3\n")
 1509 
 1510     def test3(self):
 1511         """
 1512         #return'ing an string AND streaming other output via the transaction
 1513         """
 1514         self.verify("""1
 1515 $str($test(trans=trans)[1])
 1516 3
 1517 #def test
 1518 1.5
 1519 #if 1
 1520 #return '123'
 1521 #else
 1522 aoeuoaeu
 1523 #end if
 1524 #end def
 1525 """,
 1526                     "1\n1.5\n2\n3\n")
 1527 
 1528 
 1529 class YieldDirective(OutputTest):
 1530     convertEOLs = False
 1531 
 1532     def test1(self):
 1533         """simple #yield """
 1534 
 1535         src1 = """#for i in range(10)\n#yield i\n#end for"""
 1536         src2 = """#for i in range(10)\n$i#slurp\n#yield\n#end for"""
 1537         src3 = ("#def iterator\n"
 1538                 "#for i in range(10)\n#yield i\n#end for\n"
 1539                 "#end def\n"
 1540                 "#for i in $iterator\n$i#end for"
 1541                 )
 1542 
 1543         for src in (src1, src2, src3):
 1544             klass = Template.compile(src, keepRefToGeneratedCode=True)
 1545             # print klass._CHEETAH_generatedModuleCode
 1546             iter = klass().respond()
 1547             output = [str(i) for i in iter]
 1548             assert ''.join(output) == '0123456789'
 1549             # print ''.join(output)
 1550 
 1551         # @@TR: need to expand this to cover error conditions etc.
 1552 
 1553 
 1554 class ForDirective(OutputTest):
 1555 
 1556     def test1(self):
 1557         """#for loop with one local var"""
 1558         self.verify("#for $i in range(5)\n$i\n#end for",
 1559                     "0\n1\n2\n3\n4\n")
 1560 
 1561         self.verify("#for $i in range(5):\n$i\n#end for",
 1562                     "0\n1\n2\n3\n4\n")
 1563 
 1564         self.verify("#for $i in range(5): ##comment\n$i\n#end for",
 1565                     "0\n1\n2\n3\n4\n")
 1566 
 1567         self.verify("#for $i in range(5) ##comment\n$i\n#end for",
 1568                     "0\n1\n2\n3\n4\n")
 1569 
 1570     def test2(self):
 1571         """#for loop with WS in loop"""
 1572         self.verify("#for $i in range(5)\n$i \n#end for",
 1573                     "0 \n1 \n2 \n3 \n4 \n")
 1574 
 1575     def test3(self):
 1576         """#for loop gobble WS"""
 1577         self.verify("   #for $i in range(5)   \n$i \n   #end for   ",
 1578                     "0 \n1 \n2 \n3 \n4 \n")
 1579 
 1580     def test4(self):
 1581         """#for loop over list"""
 1582         self.verify("#for $i, $j in [(0,1),(2,3)]\n$i,$j\n#end for",
 1583                     "0,1\n2,3\n")
 1584 
 1585     def test5(self):
 1586         """#for loop over list, with #slurp"""
 1587         self.verify("#for $i, $j in [(0,1),(2,3)]\n$i,$j#slurp\n#end for",
 1588                     "0,12,3")
 1589 
 1590     def test6(self):
 1591         """#for loop with explicit closures"""
 1592         self.verify("#for $i in range(5)#$i#end for#",
 1593                     "01234")
 1594 
 1595     def test7(self):
 1596         """#for loop with explicit closures and WS"""
 1597         self.verify("  #for $i in range(5)#$i#end for#  ",
 1598                     "  01234  ")
 1599 
 1600     def test8(self):
 1601         """#for loop using another $var"""
 1602         self.verify("  #for $i in range($aFunc(5))#$i#end for#  ",
 1603                     "  01234  ")
 1604 
 1605     def test9(self):
 1606         """test methods in for loops"""
 1607         self.verify("#for $func in $listOfLambdas\n$func($anInt)\n#end for",
 1608                     "1\n1\n1\n")
 1609 
 1610     def test10(self):
 1611         """#for loop over list, using methods of the items"""
 1612         self.verify(
 1613             "#for i, j in [('aa','bb'),('cc','dd')]\n"
 1614             "$i.upper,$j.upper\n#end for",
 1615             "AA,BB\nCC,DD\n")
 1616         self.verify(
 1617             "#for $i, $j in [('aa','bb'),('cc','dd')]\n"
 1618             "$i.upper,$j.upper\n#end for",
 1619             "AA,BB\nCC,DD\n")
 1620 
 1621     def test11(self):
 1622         """#for loop over list, using ($i,$j) style target list"""
 1623         self.verify(
 1624             "#for (i, j) in [('aa','bb'),('cc','dd')]\n"
 1625             "$i.upper,$j.upper\n#end for",
 1626             "AA,BB\nCC,DD\n")
 1627         self.verify(
 1628             "#for ($i, $j) in [('aa','bb'),('cc','dd')]\n"
 1629             "$i.upper,$j.upper\n#end for",
 1630             "AA,BB\nCC,DD\n")
 1631 
 1632     def test12(self):
 1633         """#for loop over list, using i, (j,k) style target list"""
 1634         self.verify(
 1635             "#for i, (j, k) in enumerate([('aa','bb'),('cc','dd')])\n"
 1636             "$j.upper,$k.upper\n#end for",
 1637             "AA,BB\nCC,DD\n")
 1638         self.verify(
 1639             "#for $i, ($j, $k) in enumerate([('aa','bb'),('cc','dd')])\n"
 1640             "$j.upper,$k.upper\n#end for",
 1641             "AA,BB\nCC,DD\n")
 1642 
 1643     def test13(self):
 1644         """single line #for"""
 1645         self.verify("#for $i in range($aFunc(5)): $i",
 1646                     "01234")
 1647 
 1648     def test14(self):
 1649         """single line #for with 1 extra leading space"""
 1650         self.verify("#for $i in range($aFunc(5)):  $i",
 1651                     " 0 1 2 3 4")
 1652 
 1653     def test15(self):
 1654         """2 times single line #for"""
 1655         self.verify("#for $i in range($aFunc(5)): $i#slurp\n"*2,  # noqa: E226,E501 missing whitespace around operator
 1656                     "01234"*2)  # noqa: E226 missing whitespace around operator
 1657 
 1658     def test16(self):
 1659         """false single line #for """
 1660         self.verify("#for $i in range(5): \n$i\n#end for",
 1661                     "0\n1\n2\n3\n4\n")
 1662 
 1663 
 1664 class RepeatDirective(OutputTest):
 1665 
 1666     def test1(self):
 1667         """basic #repeat"""
 1668         self.verify("#repeat 3\n1\n#end repeat",
 1669                     "1\n1\n1\n")
 1670         self.verify("#repeat 3: \n1\n#end repeat",
 1671                     "1\n1\n1\n")
 1672 
 1673         self.verify("#repeat 3 ##comment\n1\n#end repeat",
 1674                     "1\n1\n1\n")
 1675 
 1676         self.verify("#repeat 3: ##comment\n1\n#end repeat",
 1677                     "1\n1\n1\n")
 1678 
 1679     def test2(self):
 1680         """#repeat with numeric expression"""
 1681         self.verify("#repeat 3*3//3\n1\n#end repeat",
 1682                     "1\n1\n1\n")
 1683 
 1684     def test3(self):
 1685         """#repeat with placeholder"""
 1686         self.verify("#repeat $numTwo\n1\n#end repeat",
 1687                     "1\n1\n")
 1688 
 1689     def test4(self):
 1690         """#repeat with placeholder * num"""
 1691         self.verify("#repeat $numTwo*1\n1\n#end repeat",
 1692                     "1\n1\n")
 1693 
 1694     def test5(self):
 1695         """#repeat with placeholder and WS"""
 1696         self.verify("   #repeat $numTwo   \n1\n   #end repeat   ",
 1697                     "1\n1\n")
 1698 
 1699     def test6(self):
 1700         """single-line #repeat"""
 1701         self.verify("#repeat $numTwo: 1",
 1702                     "11")
 1703         self.verify("#repeat $numTwo: 1\n"*2,  # noqa: E226,E501 missing whitespace around operator
 1704                     "1\n1\n"*2)  # noqa: E226,E501 missing whitespace around operator
 1705 
 1706         # false single-line
 1707         self.verify("#repeat 3:  \n1\n#end repeat",
 1708                     "1\n1\n1\n")
 1709 
 1710 
 1711 class AttrDirective(OutputTest):
 1712 
 1713     def test1(self):
 1714         """#attr with int"""
 1715         self.verify("#attr $test = 1234\n$test",
 1716                     "1234")
 1717 
 1718     def test2(self):
 1719         """#attr with string"""
 1720         self.verify("#attr $test = 'blarg'\n$test",
 1721                     "blarg")
 1722 
 1723     def test3(self):
 1724         """#attr with expression"""
 1725         self.verify("#attr $test = 'blarg'.upper()*2\n$test",
 1726                     "BLARGBLARG")
 1727 
 1728     def test4(self):
 1729         """#attr with string + WS
 1730         Should gobble"""
 1731         self.verify("     #attr $test = 'blarg'   \n$test",
 1732                     "blarg")
 1733 
 1734     def test5(self):
 1735         """#attr with string + WS + leading text
 1736         Shouldn't gobble"""
 1737         self.verify("  --   #attr $test = 'blarg'   \n$test",
 1738                     "  --   \nblarg")
 1739 
 1740 
 1741 class DefDirective(OutputTest):
 1742 
 1743     def test1(self):
 1744         """#def without argstring"""
 1745         self.verify("#def testMeth\n1234\n#end def\n$testMeth",
 1746                     "1234\n")
 1747 
 1748         self.verify("#def testMeth ## comment\n1234\n#end def\n$testMeth",
 1749                     "1234\n")
 1750 
 1751         self.verify("#def testMeth: ## comment\n1234\n#end def\n$testMeth",
 1752                     "1234\n")
 1753 
 1754     def test2(self):
 1755         """#def without argstring, gobble WS"""
 1756         self.verify("   #def testMeth  \n1234\n    #end def   \n$testMeth",
 1757                     "1234\n")
 1758 
 1759     def test3(self):
 1760         """#def with argstring, gobble WS"""
 1761         self.verify(
 1762             "  #def testMeth($a=999)   \n1234-$a\n  #end def\n$testMeth",
 1763             "1234-999\n")
 1764 
 1765     def test4(self):
 1766         """#def with argstring, gobble WS, string used in call"""
 1767         self.verify(
 1768             "  #def testMeth($a=999)   \n"
 1769             "1234-$a\n  #end def\n$testMeth('ABC')",
 1770             "1234-ABC\n")
 1771 
 1772     def test5(self):
 1773         """#def with argstring, gobble WS, list used in call"""
 1774         self.verify(
 1775             "  #def testMeth($a=999)   \n"
 1776             "1234-$a\n  #end def\n$testMeth([1,2,3])",
 1777             "1234-[1, 2, 3]\n")
 1778 
 1779     def test6(self):
 1780         """#def with 2 args, gobble WS, list used in call"""
 1781         self.verify(
 1782             "  #def testMeth($a, $b='default')   \n"
 1783             "1234-$a$b\n  #end def\n$testMeth([1,2,3])",
 1784             "1234-[1, 2, 3]default\n")
 1785 
 1786     def test7(self):
 1787         """#def with *args, gobble WS"""
 1788         self.verify(
 1789             "  #def testMeth($*args)   \n1234-$args\n  #end def\n$testMeth",
 1790             "1234-()\n")
 1791 
 1792     def test8(self):
 1793         """#def with **KWs, gobble WS"""
 1794         self.verify(
 1795             "  #def testMeth($**KWs)   \n1234-$KWs\n  #end def\n$testMeth",
 1796             "1234-{}\n")
 1797 
 1798     def test9(self):
 1799         """#def with *args + **KWs, gobble WS"""
 1800         self.verify(
 1801             "  #def testMeth($*args, $**KWs)   \n"
 1802             "1234-$args-$KWs\n  #end def\n$testMeth",
 1803             "1234-()-{}\n")
 1804 
 1805     def test10(self):
 1806         """#def with *args + **KWs, gobble WS"""
 1807         self.verify(
 1808             "  #def testMeth($*args, $**KWs)   \n"
 1809             "1234-$args-$KWs.a\n  #end def\n$testMeth(1,2, a=1)",
 1810             "1234-(1, 2)-1\n")
 1811 
 1812     def test11(self):
 1813         """single line #def with extra WS"""
 1814         self.verify(
 1815             "#def testMeth: aoeuaoeu\n- $testMeth -",
 1816             "- aoeuaoeu -")
 1817 
 1818     def test12(self):
 1819         """single line #def with extra WS and nested $placeholders"""
 1820         self.verify(
 1821             "#def testMeth: $anInt $aFunc(1234)\n- $testMeth -",
 1822             "- 1 1234 -")
 1823 
 1824     def test13(self):
 1825         """single line #def escaped $placeholders"""
 1826         self.verify(
 1827             "#def testMeth: \$aFunc(\$anInt)\n- $testMeth -",
 1828             "- $aFunc($anInt) -")
 1829 
 1830     def test14(self):
 1831         """single line #def 1 escaped $placeholders"""
 1832         self.verify(
 1833             "#def testMeth: \$aFunc($anInt)\n- $testMeth -",
 1834             "- $aFunc(1) -")
 1835 
 1836     def test15(self):
 1837         """single line #def 1 escaped $placeholders + more WS"""
 1838         self.verify(
 1839             "#def testMeth    : \$aFunc($anInt)\n- $testMeth -",
 1840             "- $aFunc(1) -")
 1841 
 1842     def test16(self):
 1843         """multiline #def with $ on methodName"""
 1844         self.verify("#def $testMeth\n1234\n#end def\n$testMeth",
 1845                     "1234\n")
 1846 
 1847     def test17(self):
 1848         """single line #def with $ on methodName"""
 1849         self.verify("#def $testMeth:1234\n$testMeth",
 1850                     "1234")
 1851 
 1852     def test18(self):
 1853         """single line #def with an argument"""
 1854         self.verify("#def $testMeth($arg=1234):$arg\n$testMeth",
 1855                     "1234")
 1856 
 1857     def test19(self):
 1858         """#def that extends over two lines with arguments"""
 1859         self.verify("#def $testMeth($arg=1234,\n"
 1860                     + "  $arg2=5678)\n"
 1861                     + "$arg $arg2\n"
 1862                     + "#end def\n"
 1863                     + "$testMeth",
 1864                     "1234 5678\n")
 1865 
 1866 
 1867 class DecoratorDirective(OutputTest):
 1868     def test1(self):
 1869         """single line #def with decorator"""
 1870 
 1871         self.verify("#@ blah", "#@ blah")
 1872         self.verify("#@23 blah", "#@23 blah")
 1873         self.verify("#@@TR: comment", "#@@TR: comment")
 1874 
 1875         self.verify(
 1876             "#from Cheetah.Tests.SyntaxAndOutput import testdecorator\n"
 1877             + "#@testdecorator"
 1878             + "\n#def $testMeth():1234\n$testMeth",
 1879             "1234")
 1880 
 1881         self.verify(
 1882             "#from Cheetah.Tests.SyntaxAndOutput import testdecorator\n"
 1883             + "#@testdecorator"
 1884             + "\n#block $testMeth():1234",
 1885             "1234")
 1886 
 1887         try:
 1888             self.verify(
 1889                 "#from Cheetah.Tests.SyntaxAndOutput import testdecorator\n"
 1890                 + "#@testdecorator\n sdf"
 1891                 + "\n#def $testMeth():1234\n$testMeth",
 1892 
 1893                 "1234")
 1894         except ParseError:
 1895             pass
 1896         else:
 1897             self.fail('should raise a ParseError')
 1898 
 1899     def test2(self):
 1900         """#def with multiple decorators"""
 1901         self.verify(
 1902             "#from Cheetah.Tests.SyntaxAndOutput import testdecorator\n"
 1903             + "#@testdecorator\n"
 1904             + "#@testdecorator\n"
 1905             + "#def testMeth\n"
 1906             + "1234\n"
 1907             "#end def\n"
 1908             "$testMeth",
 1909             "1234\n")
 1910 
 1911 
 1912 class BlockDirective(OutputTest):
 1913 
 1914     def test1(self):
 1915         """#block without argstring"""
 1916         self.verify("#block testBlock\n1234\n#end block",
 1917                     "1234\n")
 1918 
 1919         self.verify("#block testBlock ##comment\n1234\n#end block",
 1920                     "1234\n")
 1921 
 1922     def test2(self):
 1923         """#block without argstring, gobble WS"""
 1924         self.verify("  #block testBlock   \n1234\n  #end block  ",
 1925                     "1234\n")
 1926 
 1927     def test3(self):
 1928         """#block with argstring, gobble WS
 1929 
 1930         Because blocks can be reused in multiple parts of the template
 1931         arguments (!!with defaults!!) can be given.
 1932         """
 1933         self.verify("  #block testBlock($a=999)   \n1234-$a\n  #end block  ",
 1934                     "1234-999\n")
 1935 
 1936     def test4(self):
 1937         """#block with 2 args, gobble WS"""
 1938         self.verify(
 1939             "  #block testBlock($a=999, $b=444)   \n1234-$a$b\n  #end block  ",
 1940             "1234-999444\n")
 1941 
 1942     def test5(self):
 1943         """#block with 2 nested blocks
 1944 
 1945         Blocks can be nested to any depth and the name of the block is optional
 1946         for the #end block part: #end block OR #end block [name] """
 1947 
 1948         self.verify("""#block testBlock
 1949 this is a test block
 1950 #block outerNest
 1951 outer
 1952 #block innerNest
 1953 inner
 1954 #end block innerNest
 1955 #end block outerNest
 1956 ---
 1957 #end block testBlock
 1958 """,
 1959                     "this is a test block\nouter\ninner\n---\n")
 1960 
 1961     def test6(self):
 1962         """single line #block """
 1963         self.verify(
 1964             "#block testMeth: This is my block",
 1965             "This is my block")
 1966 
 1967     def test7(self):
 1968         """single line #block with WS"""
 1969         self.verify(
 1970             "#block testMeth: This is my block",
 1971             "This is my block")
 1972 
 1973     def test8(self):
 1974         """single line #block 1 escaped $placeholders"""
 1975         self.verify(
 1976             "#block testMeth: \$aFunc($anInt)",
 1977             "$aFunc(1)")
 1978 
 1979     def test9(self):
 1980         """single line #block 1 escaped $placeholders + WS"""
 1981         self.verify(
 1982             "#block testMeth: \$aFunc( $anInt )",
 1983             "$aFunc( 1 )")
 1984 
 1985     def test10(self):
 1986         """single line #block 1 escaped $placeholders + more WS"""
 1987         self.verify(
 1988             "#block testMeth  : \$aFunc( $anInt )",
 1989             "$aFunc( 1 )")
 1990 
 1991     def test11(self):
 1992         """multiline #block $ on argstring"""
 1993         self.verify("#block $testBlock\n1234\n#end block",
 1994                     "1234\n")
 1995 
 1996     def test12(self):
 1997         """single line #block with $ on methodName """
 1998         self.verify(
 1999             "#block $testMeth: This is my block",
 2000             "This is my block")
 2001 
 2002     def test13(self):
 2003         """single line #block with an arg """
 2004         self.verify(
 2005             "#block $testMeth($arg='This is my block'): $arg",
 2006             "This is my block")
 2007 
 2008     def test14(self):
 2009         """single line #block with None for content"""
 2010         self.verify(
 2011             """#block $testMeth: $None\ntest $testMeth-""",
 2012             "test -")
 2013 
 2014     def test15(self):
 2015         """single line #block with nothing for content"""
 2016         self.verify(
 2017             """#block $testMeth: \nfoo\n#end block\ntest $testMeth-""",
 2018             "foo\ntest foo\n-")
 2019 
 2020 
 2021 class IncludeDirective(OutputTest):
 2022 
 2023     def setUp(self):
 2024         fp = open('parseTest.txt', 'w')
 2025         fp.write("$numOne $numTwo")
 2026         fp.flush()
 2027         fp.close()
 2028 
 2029     def tearDown(self):
 2030         if os.path.exists('parseTest.txt'):
 2031             os.remove('parseTest.txt')
 2032 
 2033     def test1(self):
 2034         """#include raw of source $emptyString"""
 2035         self.verify("#include raw source=$emptyString",
 2036                     "")
 2037 
 2038     def test2(self):
 2039         """#include raw of source $blockToBeParsed"""
 2040         self.verify("#include raw source=$blockToBeParsed",
 2041                     "$numOne $numTwo")
 2042 
 2043     def test3(self):
 2044         """#include raw of 'parseTest.txt'"""
 2045         self.verify("#include raw 'parseTest.txt'",
 2046                     "$numOne $numTwo")
 2047 
 2048     def test4(self):
 2049         """#include raw of $includeFileName"""
 2050         self.verify("#include raw $includeFileName",
 2051                     "$numOne $numTwo")
 2052 
 2053     def test5(self):
 2054         """#include raw of $includeFileName, with WS"""
 2055         self.verify("       #include raw $includeFileName      ",
 2056                     "$numOne $numTwo")
 2057 
 2058     def test6(self):
 2059         """#include raw of source= , with WS"""
 2060         self.verify("       #include raw source='This is my $Source '*2      ",
 2061                     "This is my $Source This is my $Source ")
 2062 
 2063     def test7(self):
 2064         """#include of $blockToBeParsed"""
 2065         self.verify("#include source=$blockToBeParsed",
 2066                     "1 2")
 2067 
 2068     def test8(self):
 2069         """#include of $blockToBeParsed, with WS"""
 2070         self.verify("   #include source=$blockToBeParsed   ",
 2071                     "1 2")
 2072 
 2073     def test9(self):
 2074         """#include of 'parseTest.txt', with WS"""
 2075         self.verify("   #include source=$blockToBeParsed   ",
 2076                     "1 2")
 2077 
 2078     def test10(self):
 2079         """#include of "parseTest.txt", with WS"""
 2080         self.verify("   #include source=$blockToBeParsed   ",
 2081                     "1 2")
 2082 
 2083     def test11(self):
 2084         """#include of 'parseTest.txt', with WS and surrounding text"""
 2085         self.verify("aoeu\n  #include source=$blockToBeParsed  \naoeu",
 2086                     "aoeu\n1 2aoeu")
 2087 
 2088     def test12(self):
 2089         """#include of 'parseTest.txt', with WS and explicit closure"""
 2090         self.verify("  #include source=$blockToBeParsed#  ",
 2091                     "  1 2  ")
 2092 
 2093 
 2094 class SilentDirective(OutputTest):
 2095 
 2096     def _X_test1(self):
 2097         """simple #silent"""
 2098         self.verify("#silent $aFunc",
 2099                     "")
 2100 
 2101     def _X_test2(self):
 2102         """simple #silent"""
 2103         self.verify("#silent $anObj.callIt\n$anObj.callArg",
 2104                     "1234")
 2105 
 2106         self.verify("#silent $anObj.callIt ##comment\n$anObj.callArg",
 2107                     "1234")
 2108 
 2109     def _X_test3(self):
 2110         """simple #silent"""
 2111         self.verify("#silent $anObj.callIt(99)\n$anObj.callArg",
 2112                     "99")
 2113 
 2114     def test4(self):
 2115         """#silent 1234
 2116         """
 2117         self.verify("#silent 1234",
 2118                     "")
 2119 
 2120 
 2121 class SetDirective(OutputTest):
 2122 
 2123     def test1(self):
 2124         """simple #set"""
 2125         self.verify("#set $testVar = 'blarg'\n$testVar",
 2126                     "blarg")
 2127         self.verify("#set testVar = 'blarg'\n$testVar",
 2128                     "blarg")
 2129 
 2130         self.verify("#set testVar = 'blarg'##comment\n$testVar",
 2131                     "blarg")
 2132 
 2133     def test2(self):
 2134         """simple #set with no WS between operands"""
 2135         self.verify("#set       $testVar='blarg'",
 2136                     "")
 2137 
 2138     def test3(self):
 2139         """#set + use of var"""
 2140         self.verify("#set $testVar = 'blarg'\n$testVar",
 2141                     "blarg")
 2142 
 2143     def test4(self):
 2144         """#set + use in an #include"""
 2145         self.verify(
 2146             "#set global $aSetVar = 1234\n#include source=$includeBlock2",
 2147             "1 2 1234")
 2148 
 2149     def test5(self):
 2150         """#set with a dictionary"""
 2151         self.verify("""#set $testDict = {'one':'one1','two':'two2','three':'three3'}
 2152 $testDict.one
 2153 $testDict.two""",
 2154                     "one1\ntwo2")
 2155 
 2156     def test6(self):
 2157         """#set with string, then used in #if block"""
 2158 
 2159         self.verify("""#set $test='a string'\n#if $test#blarg#end if""",
 2160                     "blarg")
 2161 
 2162     def test7(self):
 2163         """simple #set, gobble WS"""
 2164         self.verify("   #set $testVar = 'blarg'   ",
 2165                     "")
 2166 
 2167     def test8(self):
 2168         """simple #set, don't gobble WS"""
 2169         self.verify("  #set $testVar = 'blarg'#---",
 2170                     "  ---")
 2171 
 2172     def test9(self):
 2173         """simple #set with a list"""
 2174         self.verify("   #set $testVar = [1, 2, 3]  \n$testVar",
 2175                     "[1, 2, 3]")
 2176 
 2177     def test10(self):
 2178         """simple #set global with a list"""
 2179         self.verify("   #set global $testVar = [1, 2, 3]  \n$testVar",
 2180                     "[1, 2, 3]")
 2181 
 2182     def test11(self):
 2183         """simple #set global with a list and *cache
 2184 
 2185         Caching only works with global #set vars.  Local vars are not accesible
 2186         to the cache namespace.
 2187         """
 2188 
 2189         self.verify("   #set global $testVar = [1, 2, 3]  \n$*testVar",
 2190                     "[1, 2, 3]")
 2191 
 2192     def test12(self):
 2193         """simple #set global with a list and *<int>*cache"""
 2194         self.verify("   #set global $testVar = [1, 2, 3]  \n$*5*testVar",
 2195                     "[1, 2, 3]")
 2196 
 2197     def test13(self):
 2198         """simple #set with a list and *<float>*cache"""
 2199         self.verify("   #set global $testVar = [1, 2, 3]  \n$*.5*testVar",
 2200                     "[1, 2, 3]")
 2201 
 2202     def test14(self):
 2203         """simple #set without NameMapper on"""
 2204         self.verify(
 2205             """#compiler useNameMapper = 0\n#set $testVar = 1 \n$testVar""",
 2206             "1")
 2207 
 2208     def test15(self):
 2209         """simple #set without $"""
 2210         self.verify("""#set testVar = 1 \n$testVar""",
 2211                     "1")
 2212 
 2213     def test16(self):
 2214         """simple #set global without $"""
 2215         self.verify("""#set global testVar = 1 \n$testVar""",
 2216                     "1")
 2217 
 2218     def test17(self):
 2219         """simple #set module without $"""
 2220         self.verify("""#set module __foo__ = 'bar'\n$__foo__""",
 2221                     "bar")
 2222 
 2223     def test18(self):
 2224         """#set with i,j=list style assignment"""
 2225         self.verify("""#set i,j = [1,2]\n$i$j""",
 2226                     "12")
 2227         self.verify("""#set $i,$j = [1,2]\n$i$j""",
 2228                     "12")
 2229 
 2230     def test19(self):
 2231         """#set with (i,j)=list style assignment"""
 2232         self.verify("""#set (i,j) = [1,2]\n$i$j""",
 2233                     "12")
 2234         self.verify("""#set ($i,$j) = [1,2]\n$i$j""",
 2235                     "12")
 2236 
 2237     def test20(self):
 2238         """#set with i, (j,k)=list style assignment"""
 2239         self.verify("""#set i, (j,k) = [1,(2,3)]\n$i$j$k""",
 2240                     "123")
 2241         self.verify("""#set $i, ($j,$k) = [1,(2,3)]\n$i$j$k""",
 2242                     "123")
 2243 
 2244 
 2245 class IfDirective(OutputTest):
 2246 
 2247     def test1(self):
 2248         """simple #if block"""
 2249         self.verify("#if 1\n$aStr\n#end if\n",
 2250                     "blarg\n")
 2251 
 2252         self.verify("#if 1:\n$aStr\n#end if\n",
 2253                     "blarg\n")
 2254 
 2255         self.verify("#if 1:   \n$aStr\n#end if\n",
 2256                     "blarg\n")
 2257 
 2258         self.verify("#if 1: ##comment \n$aStr\n#end if\n",
 2259                     "blarg\n")
 2260 
 2261         self.verify("#if 1 ##comment \n$aStr\n#end if\n",
 2262                     "blarg\n")
 2263 
 2264         self.verify("#if 1##for i in range(10)#$i#end for##end if",
 2265                     '0123456789')
 2266 
 2267         self.verify("#if 1: #for i in range(10)#$i#end for",
 2268                     '0123456789')
 2269 
 2270         self.verify("#if 1: #for i in range(10):$i",
 2271                     '0123456789')
 2272 
 2273     def test2(self):
 2274         """simple #if block, with WS"""
 2275         self.verify("   #if 1\n$aStr\n  #end if  \n",
 2276                     "blarg\n")
 2277 
 2278     def test3(self):
 2279         """simple #if block, with WS and explicit closures"""
 2280         self.verify("   #if 1#\n$aStr\n  #end if #--\n",
 2281                     "   \nblarg\n  --\n")
 2282 
 2283     def test4(self):
 2284         """#if block using $numOne"""
 2285         self.verify("#if $numOne\n$aStr\n#end if\n",
 2286                     "blarg\n")
 2287 
 2288     def test5(self):
 2289         """#if block using $zero"""
 2290         self.verify("#if $zero\n$aStr\n#end if\n",
 2291                     "")
 2292 
 2293     def test6(self):
 2294         """#if block using $emptyString"""
 2295         self.verify("#if $emptyString\n$aStr\n#end if\n",
 2296                     "")
 2297 
 2298     def test7(self):
 2299         """#if ... #else ... block using a $emptyString"""
 2300         self.verify(
 2301             "#if $emptyString\n$anInt\n#else\n$anInt - $anInt\n#end if",
 2302             "1 - 1\n")
 2303 
 2304     def test8(self):
 2305         """#if ... #elif ... #else ... block using a $emptyString"""
 2306         self.verify(
 2307             "#if $emptyString\n$c\n"
 2308             "#elif $numOne\n$numOne\n#else\n$c - $c\n#end if",
 2309             "1\n")
 2310 
 2311     def test9(self):
 2312         """#if 'not' test, with #slurp"""
 2313         self.verify("#if not $emptyString\n$aStr#slurp\n#end if\n",
 2314                     "blarg")
 2315 
 2316     def test10(self):
 2317         """#if block using $*emptyString
 2318 
 2319         This should barf
 2320         """
 2321         try:
 2322             self.verify("#if $*emptyString\n$aStr\n#end if\n",
 2323                         "")
 2324         except ParseError:
 2325             pass
 2326         else:
 2327             self.fail('This should barf')
 2328 
 2329     def test11(self):
 2330         """
 2331         #if block using invalid top-level $(placeholder) syntax - should barf
 2332         """
 2333 
 2334         for badSyntax in ("#if $*5*emptyString\n$aStr\n#end if\n",
 2335                           "#if ${emptyString}\n$aStr\n#end if\n",
 2336                           "#if $(emptyString)\n$aStr\n#end if\n",
 2337                           "#if $[emptyString]\n$aStr\n#end if\n",
 2338                           "#if $!emptyString\n$aStr\n#end if\n",
 2339                           ):
 2340             try:
 2341                 self.verify(badSyntax, "")
 2342             except ParseError:
 2343                 pass
 2344             else:
 2345                 self.fail('This should barf')
 2346 
 2347     def test12(self):
 2348         """#if ... #else if ... #else ... block using a $emptyString
 2349         Same as test 8 but using else if instead of elif"""
 2350         self.verify(
 2351             "#if $emptyString\n$c\n#else "
 2352             "if $numOne\n$numOne\n#else\n$c - $c\n#end if",
 2353             "1\n")
 2354 
 2355     def test13(self):
 2356         """#if# ... #else # ... block using a $emptyString with """
 2357         self.verify("#if $emptyString# $anInt#else#$anInt - $anInt#end if",
 2358                     "1 - 1")
 2359 
 2360     def test14(self):
 2361         """single-line #if: simple"""
 2362         self.verify("#if $emptyString then 'true' else 'false'",
 2363                     "false")
 2364 
 2365     def test15(self):
 2366         """single-line #if: more complex"""
 2367         self.verify("#if $anInt then 'true' else 'false'",
 2368                     "true")
 2369 
 2370     def test16(self):
 2371         """single-line #if: with the words 'else' and 'then' in the output """
 2372         self.verify(
 2373             "#if ($anInt and not $emptyString==''' else ''') "
 2374             "then $str('then') else 'else'",
 2375             "then")
 2376 
 2377     def test17(self):
 2378         """single-line #if:  """
 2379         self.verify("#if 1: foo\n#if 0: bar\n#if 1: foo",
 2380                     "foo\nfoo")
 2381 
 2382         self.verify("#if 1: foo\n#if 0: bar\n#if 1: foo",
 2383                     "foo\nfoo")
 2384 
 2385     def test18(self):
 2386         """single-line #if: \n#else: """
 2387         self.verify("#if 1: foo\n#elif 0: bar",
 2388                     "foo\n")
 2389 
 2390         self.verify("#if 1: foo\n#elif 0: bar\n#else: blarg\n",
 2391                     "foo\n")
 2392 
 2393         self.verify("#if 0: foo\n#elif 0: bar\n#else: blarg\n",
 2394                     "blarg\n")
 2395 
 2396 
 2397 class UnlessDirective(OutputTest):
 2398 
 2399     def test1(self):
 2400         """#unless 1"""
 2401         self.verify("#unless 1\n 1234 \n#end unless",
 2402                     "")
 2403 
 2404         self.verify("#unless 1:\n 1234 \n#end unless",
 2405                     "")
 2406 
 2407         self.verify("#unless 1: ##comment\n 1234 \n#end unless",
 2408                     "")
 2409 
 2410         self.verify("#unless 1 ##comment\n 1234 \n#end unless",
 2411                     "")
 2412 
 2413     def test2(self):
 2414         """#unless 0"""
 2415         self.verify("#unless 0\n 1234 \n#end unless",
 2416                     " 1234 \n")
 2417 
 2418     def test3(self):
 2419         """#unless $none"""
 2420         self.verify("#unless $none\n 1234 \n#end unless",
 2421                     " 1234 \n")
 2422 
 2423     def test4(self):
 2424         """#unless $numTwo"""
 2425         self.verify("#unless $numTwo\n 1234 \n#end unless",
 2426                     "")
 2427 
 2428     def test5(self):
 2429         """#unless $numTwo with WS"""
 2430         self.verify("   #unless $numTwo   \n 1234 \n    #end unless   ",
 2431                     "")
 2432 
 2433     def test6(self):
 2434         """single-line #unless"""
 2435         self.verify("#unless 1: 1234", "")
 2436         self.verify("#unless 0: 1234", "1234")
 2437         self.verify("#unless 0: 1234\n"*2, "1234\n"*2)  # noqa: E226,E501 missing whitespace around operator
 2438 
 2439 
 2440 class PSP(OutputTest):
 2441     def searchList(self):
 2442         return None
 2443 
 2444     def test1(self):
 2445         """simple <%= [int] %>"""
 2446         self.verify("<%= 1234 %>", "1234")
 2447 
 2448     def test2(self):
 2449         """simple <%= [string] %>"""
 2450         self.verify("<%= 'blarg' %>", "blarg")
 2451 
 2452     def test3(self):
 2453         """simple <%= None %>"""
 2454         self.verify("<%= None %>", "")
 2455 
 2456     def test4(self):
 2457         """simple <%= [string] %> + $anInt"""
 2458         self.verify("<%= 'blarg' %>$anInt", "blarg1")
 2459 
 2460     def test5(self):
 2461         """simple <%= [EXPR] %> + $anInt"""
 2462         self.verify("<%= ('blarg'*2).upper() %>$anInt", "BLARGBLARG1")
 2463 
 2464     def test6(self):
 2465         """for loop in <%%>"""
 2466         self.verify("<% for i in range(5):%>1<%end%>", "11111")
 2467 
 2468     def test7(self):
 2469         """for loop in <%%> and using <%=i%>"""
 2470         self.verify("<% for i in range(5):%><%=i%><%end%>", "01234")
 2471 
 2472     def test8(self):
 2473         """for loop in <% $%> and using <%=i%>"""
 2474         self.verify("""<% for i in range(5):
 2475     i=i*2$%><%=i%><%end%>""", "02468")
 2476 
 2477     def test9(self):
 2478         """for loop in <% $%> and using <%=i%> plus extra text"""
 2479         self.verify("""<% for i in range(5):
 2480     i=i*2$%><%=i%>-<%end%>""", "0-2-4-6-8-")
 2481 
 2482     def test10(self):
 2483         """ Using getVar and write within a PSP """
 2484         self._searchList = [{'me': 1}]
 2485         template = '''This is my template
 2486 <%
 2487 me = self.getVar('me')
 2488 if isinstance(me, int):
 2489     write('Bork')
 2490 else:
 2491     write('Nork')
 2492 %>'''
 2493         self.verify(template, 'This is my template\nBork')
 2494 
 2495 
 2496 class WhileDirective(OutputTest):
 2497     def test1(self):
 2498         """simple #while with a counter"""
 2499         self.verify(
 2500             "#set $i = 0\n#while $i < 5\n$i#slurp\n#set $i += 1\n#end while",
 2501             "01234")
 2502 
 2503 
 2504 class ContinueDirective(OutputTest):
 2505     def test1(self):
 2506         """#continue with a #while"""
 2507         self.verify("""#set $i = 0
 2508 #while $i < 5
 2509 #if $i == 3
 2510   #set $i += 1
 2511   #continue
 2512 #end if
 2513 $i#slurp
 2514 #set $i += 1
 2515 #end while""",
 2516                     "0124")
 2517 
 2518     def test2(self):
 2519         """#continue with a #for"""
 2520         self.verify("""#for $i in range(5)
 2521 #if $i == 3
 2522   #continue
 2523 #end if
 2524 $i#slurp
 2525 #end for""",
 2526                     "0124")
 2527 
 2528 
 2529 class BreakDirective(OutputTest):
 2530     def test1(self):
 2531         """#break with a #while"""
 2532         self.verify("""\
 2533 #set $i = 0
 2534 #while $i < 5
 2535 #if $i == 3
 2536   #break
 2537 #end if
 2538 $i#slurp
 2539 #set $i += 1
 2540 #end while""",
 2541                     "012")
 2542 
 2543     def test2(self):
 2544         """#break with a #for"""
 2545         self.verify("""\
 2546 #for $i in range(5)
 2547 #if $i == 3
 2548   #break
 2549 #end if
 2550 $i#slurp
 2551 #end for""",
 2552                     "012")
 2553 
 2554 
 2555 class TryDirective(OutputTest):
 2556 
 2557     def test1(self):
 2558         """simple #try
 2559         """
 2560         self.verify("#try\n1234\n#except\nblarg\n#end try",
 2561                     "1234\n")
 2562 
 2563     def test2(self):
 2564         """#try / #except with #raise
 2565         """
 2566         self.verify("#try\n#raise ValueError\n#except\nblarg\n#end try",
 2567                     "blarg\n")
 2568 
 2569     def test3(self):
 2570         """#try / #except with #raise + WS
 2571 
 2572         Should gobble
 2573         """
 2574         self.verify(
 2575             "  #try  \n  #raise ValueError \n  #except \nblarg\n  #end try",
 2576             "blarg\n")
 2577 
 2578     def test4(self):
 2579         """#try / #except with #raise + WS and leading text
 2580 
 2581         Shouldn't gobble
 2582         """
 2583         self.verify(
 2584             "--#try  \n  #raise ValueError \n  #except \nblarg\n  #end try#--",
 2585             "--\nblarg\n  --")
 2586 
 2587     def test5(self):
 2588         """nested #try / #except with #raise
 2589         """
 2590         self.verify("""\
 2591 #try
 2592   #raise ValueError
 2593 #except
 2594   #try
 2595    #raise ValueError
 2596   #except
 2597 blarg
 2598   #end try
 2599 #end try""",  # noqa
 2600                     "blarg\n")
 2601 
 2602 
 2603 class PassDirective(OutputTest):
 2604     def test1(self):
 2605         """#pass in a #try / #except block
 2606         """
 2607         self.verify("#try\n#raise ValueError\n#except\n#pass\n#end try",
 2608                     "")
 2609 
 2610     def test2(self):
 2611         """#pass in a #try / #except block + WS
 2612         """
 2613         self.verify(
 2614             "  #try  \n  #raise ValueError  \n  "
 2615             "#except  \n   #pass   \n   #end try",
 2616             "")
 2617 
 2618 
 2619 class AssertDirective(OutputTest):
 2620     def test1(self):
 2621         """simple #assert
 2622         """
 2623         self.verify("#set $x = 1234\n#assert $x == 1234",
 2624                     "")
 2625 
 2626     def test2(self):
 2627         """simple #assert that fails
 2628         """
 2629         def test(self=self):
 2630             self.verify("#set $x = 1234\n#assert $x == 999",
 2631                         ""),
 2632         self.assertRaises(AssertionError, test)
 2633 
 2634     def test3(self):
 2635         """simple #assert with WS
 2636         """
 2637         self.verify("#set $x = 1234\n   #assert $x == 1234   ",
 2638                     "")
 2639 
 2640 
 2641 class RaiseDirective(OutputTest):
 2642     def test1(self):
 2643         """simple #raise ValueError
 2644 
 2645         Should raise ValueError
 2646         """
 2647         def test(self=self):
 2648             self.verify("#raise ValueError",
 2649                         ""),
 2650         self.assertRaises(ValueError, test)
 2651 
 2652     def test2(self):
 2653         """#raise ValueError in #if block
 2654 
 2655         Should raise ValueError
 2656         """
 2657         def test(self=self):
 2658             self.verify("#if 1\n#raise ValueError\n#end if\n",
 2659                         "")
 2660         self.assertRaises(ValueError, test)
 2661 
 2662     def test3(self):
 2663         """#raise ValueError in #if block
 2664 
 2665         Shouldn't raise ValueError
 2666         """
 2667         self.verify("#if 0\n#raise ValueError\n#else\nblarg#end if\n",
 2668                     "blarg\n")
 2669 
 2670 
 2671 class ImportDirective(OutputTest):
 2672     def test1(self):
 2673         """#import math
 2674         """
 2675         self.verify("#import math",
 2676                     "")
 2677 
 2678     def test2(self):
 2679         """#import math + WS
 2680 
 2681         Should gobble
 2682         """
 2683         self.verify("    #import math    ",
 2684                     "")
 2685 
 2686     def test3(self):
 2687         """#import math + WS + leading text
 2688 
 2689         Shouldn't gobble
 2690         """
 2691         self.verify("  --  #import math    ",
 2692                     "  --  ")
 2693 
 2694     def test4(self):
 2695         """#from math import syn
 2696         """
 2697         self.verify("#from math import cos",
 2698                     "")
 2699 
 2700     def test5(self):
 2701         """#from math import cos  + WS
 2702         Should gobble
 2703         """
 2704         self.verify("    #from math import cos  ",
 2705                     "")
 2706 
 2707     def test6(self):
 2708         """#from math import cos  + WS + leading text
 2709         Shouldn't gobble
 2710         """
 2711         self.verify("  --  #from math import cos  ",
 2712                     "  --  ")
 2713 
 2714     def test7(self):
 2715         """#from math import cos -- use it
 2716         """
 2717         self.verify("#from math import cos\n$cos(0)",
 2718                     "1.0")
 2719 
 2720     def test8(self):
 2721         """#from math import cos,tan,sin -- and use them
 2722         """
 2723         self.verify("#from math import cos, tan, sin\n$cos(0)-$tan(0)-$sin(0)",
 2724                     "1.0-0.0-0.0")
 2725 
 2726     def test9(self):
 2727         """#import os.path -- use it
 2728         """
 2729 
 2730         self.verify("#import os.path\n$os.path.exists('.')",
 2731                     repr(True))
 2732 
 2733     def test10(self):
 2734         """#import os.path -- use it with NameMapper turned off
 2735         """
 2736         self.verify("""##
 2737 #compiler-settings
 2738 useNameMapper=False
 2739 #end compiler-settings
 2740 #import os.path
 2741 $os.path.exists('.')""",
 2742                     repr(True))
 2743 
 2744     def test11(self):
 2745         """#from math import *
 2746         """
 2747 
 2748         self.verify("#from math import *\n$pow(1,2) $log10(10)",
 2749                     "1.0 1.0")
 2750 
 2751 
 2752 class CompilerDirective(OutputTest):
 2753     def test1(self):
 2754         """overriding the commentStartToken
 2755         """
 2756         self.verify("""$anInt##comment
 2757 #compiler commentStartToken = '//'
 2758 $anInt//comment
 2759 """,
 2760                     "1\n1\n")
 2761 
 2762     def test2(self):
 2763         """overriding and resetting the commentStartToken
 2764         """
 2765         self.verify("""$anInt##comment
 2766 #compiler commentStartToken = '//'
 2767 $anInt//comment
 2768 #compiler reset
 2769 $anInt//comment
 2770 """,
 2771                     "1\n1\n1//comment\n")
 2772 
 2773 
 2774 class CompilerSettingsDirective(OutputTest):
 2775 
 2776     def test1(self):
 2777         """overriding the cheetahVarStartToken
 2778         """
 2779         self.verify("""$anInt
 2780 #compiler-settings
 2781 cheetahVarStartToken = @
 2782 #end compiler-settings
 2783 @anInt
 2784 #compiler-settings reset
 2785 $anInt
 2786 """,
 2787                     "1\n1\n1\n")
 2788 
 2789     def test2(self):
 2790         """overriding the directiveStartToken
 2791         """
 2792         self.verify("""#set $x = 1234
 2793 $x
 2794 #compiler-settings
 2795 directiveStartToken = @
 2796 #end compiler-settings
 2797 @set $x = 1234
 2798 $x
 2799 """,
 2800                     "1234\n1234\n")
 2801 
 2802     def test3(self):
 2803         """overriding the commentStartToken
 2804         """
 2805         self.verify("""$anInt##comment
 2806 #compiler-settings
 2807 commentStartToken = //
 2808 #end compiler-settings
 2809 $anInt//comment
 2810 """,
 2811                     "1\n1\n")
 2812 
 2813 
 2814 if sys.platform.startswith('java'):
 2815     del CompilerDirective
 2816     del CompilerSettingsDirective
 2817 
 2818 
 2819 class ExtendsDirective(OutputTest):
 2820 
 2821     def test1(self):
 2822         """#extends Cheetah.Templates._SkeletonPage"""
 2823         self.verify("""#from Cheetah.Templates._SkeletonPage import _SkeletonPage
 2824 #extends _SkeletonPage
 2825 #implements respond
 2826 $spacer()
 2827 """,
 2828                     '<img src="spacer.gif" width="1" height="1" alt="" />\n')
 2829 
 2830         self.verify("""#from Cheetah.Templates._SkeletonPage import _SkeletonPage
 2831 #extends _SkeletonPage
 2832 #implements respond(foo=1234)
 2833 $spacer()$foo
 2834 """,
 2835                     '<img src="spacer.gif" width="1" height="1" alt="" />'
 2836                     '1234\n')
 2837 
 2838     def test2(self):
 2839         """#extends Cheetah.Templates.SkeletonPage without #import"""
 2840         self.verify("""#extends Cheetah.Templates.SkeletonPage
 2841 #implements respond
 2842 $spacer()
 2843 """,
 2844                     '<img src="spacer.gif" width="1" height="1" alt="" />\n')
 2845 
 2846     def test3(self):
 2847         """
 2848         #extends Cheetah.Templates.SkeletonPage.SkeletonPage without #import
 2849         """
 2850         self.verify("""#extends Cheetah.Templates.SkeletonPage.SkeletonPage
 2851 #implements respond
 2852 $spacer()
 2853 """,
 2854                     '<img src="spacer.gif" width="1" height="1" alt="" />\n')
 2855 
 2856     def test4(self):
 2857         """#extends with globals and searchList test"""
 2858         self.verify("""#extends Cheetah.Templates.SkeletonPage
 2859 #set global g="Hello"
 2860 #implements respond
 2861 $g $numOne
 2862 """,
 2863                     'Hello 1\n')
 2864 
 2865 
 2866 class SuperDirective(OutputTest):
 2867     def test1(self):
 2868         tmpl1 = Template.compile('''$foo $bar(99)
 2869         #def foo: this is base foo
 2870         #def bar(arg): super-$arg''')
 2871 
 2872         tmpl2 = tmpl1.subclass('''
 2873         #implements dummy
 2874         #def foo
 2875           #super
 2876           This is child foo
 2877           #super(trans=trans)
 2878           $bar(1234)
 2879         #end def
 2880         #def bar(arg): #super($arg)
 2881         ''')
 2882         expected = ('this is base foo          '
 2883                     'This is child foo\nthis is base foo          '
 2884                     'super-1234\n super-99')
 2885         assert str(tmpl2()).strip() == expected
 2886 
 2887 
 2888 class ImportantExampleCases(OutputTest):
 2889     def test1(self):
 2890         """how to make a comma-delimited list"""
 2891         self.verify("""#set $sep = ''
 2892 #for $letter in $letterList
 2893 $sep$letter#slurp
 2894 #set $sep = ', '
 2895 #end for
 2896 """,
 2897                     "a, b, c")
 2898 
 2899 
 2900 class FilterDirective(OutputTest):
 2901     convertEOLs = False
 2902 
 2903     def _getCompilerSettings(self):
 2904         return {'useFilterArgsInPlaceholders': True}
 2905 
 2906     def test1(self):
 2907         """#filter Filter
 2908         """
 2909         self.verify("#filter Filter\n$none#end filter",
 2910                     "")
 2911 
 2912         self.verify("#filter Filter: $none",
 2913                     "")
 2914 
 2915     def test2(self):
 2916         """#filter ReplaceNone with WS
 2917         """
 2918         self.verify("#filter Filter  \n$none#end filter",
 2919                     "")
 2920 
 2921     def test3(self):
 2922         """#filter MaxLen -- maxlen of 5"""
 2923 
 2924         self.verify("#filter MaxLen  \n${tenDigits, $maxlen=5}#end filter",
 2925                     "12345")
 2926 
 2927     def test4(self):
 2928         """#filter MaxLen -- no maxlen
 2929         """
 2930         self.verify("#filter MaxLen  \n${tenDigits}#end filter",
 2931                     "1234567890")
 2932 
 2933     def test5(self):
 2934         """#filter WebSafe -- basic usage
 2935         """
 2936         self.verify("#filter WebSafe  \n$webSafeTest#end filter",
 2937                     "abc &lt;=&gt; &amp;")
 2938 
 2939     def test6(self):
 2940         """#filter WebSafe -- also space
 2941         """
 2942         self.verify("#filter WebSafe  \n${webSafeTest, $also=' '}#end filter",
 2943                     "abc&nbsp;&lt;=&gt;&nbsp;&amp;")
 2944 
 2945     def test7(self):
 2946         """#filter WebSafe -- also space, without $ on the args
 2947         """
 2948         self.verify("#filter WebSafe  \n${webSafeTest, also=' '}#end filter",
 2949                     "abc&nbsp;&lt;=&gt;&nbsp;&amp;")
 2950 
 2951     def test8(self):
 2952         """#filter Strip -- trailing newline
 2953         """
 2954         self.verify("#filter Strip\n$strip1#end filter",
 2955                     "strippable whitespace\n")
 2956 
 2957     def test9(self):
 2958         """#filter Strip -- no trailing newine
 2959         """
 2960         self.verify("#filter Strip\n$strip2#end filter",
 2961                     "strippable whitespace")
 2962 
 2963     def test10(self):
 2964         """#filter Strip -- multi-line
 2965         """
 2966         self.verify("#filter Strip\n$strip3#end filter",
 2967                     "strippable whitespace\n1 2  3\n")
 2968 
 2969     def test11(self):
 2970         """#filter StripSqueeze -- canonicalize all whitespace to ' '
 2971         """
 2972         self.verify("#filter StripSqueeze\n$strip3#end filter",
 2973                     "strippable whitespace 1 2 3")
 2974 
 2975 
 2976 class EchoDirective(OutputTest):
 2977     def test1(self):
 2978         """#echo 1234
 2979         """
 2980         self.verify("#echo 1234",
 2981                     "1234")
 2982 
 2983 
 2984 class ErrorCatcherDirective(OutputTest):
 2985     pass
 2986 
 2987 
 2988 class VarExists(OutputTest):               # Template.varExists()
 2989 
 2990     def test1(self):
 2991         """$varExists('$anInt')
 2992         """
 2993         self.verify("$varExists('$anInt')",
 2994                     repr(True))
 2995 
 2996     def test2(self):
 2997         """$varExists('anInt')
 2998         """
 2999         self.verify("$varExists('anInt')",
 3000                     repr(True))
 3001 
 3002     def test3(self):
 3003         """$varExists('$anInt')
 3004         """
 3005         self.verify("$varExists('$bogus')",
 3006                     repr(False))
 3007 
 3008     def test4(self):
 3009         """$varExists('$anInt') combined with #if false
 3010         """
 3011         self.verify("#if $varExists('$bogus')\n1234\n#else\n999\n#end if",
 3012                     "999\n")
 3013 
 3014     def test5(self):
 3015         """$varExists('$anInt') combined with #if true
 3016         """
 3017         self.verify("#if $varExists('$anInt')\n1234\n#else\n999#end if",
 3018                     "1234\n")
 3019 
 3020 
 3021 class GetVar(OutputTest):               # Template.getVar()
 3022     def test1(self):
 3023         """$getVar('$anInt')
 3024         """
 3025         self.verify("$getVar('$anInt')",
 3026                     "1")
 3027 
 3028     def test2(self):
 3029         """$getVar('anInt')
 3030         """
 3031         self.verify("$getVar('anInt')",
 3032                     "1")
 3033 
 3034     def test3(self):
 3035         """$self.getVar('anInt')
 3036         """
 3037         self.verify("$self.getVar('anInt')",
 3038                     "1")
 3039 
 3040     def test4(self):
 3041         """$getVar('bogus', 1234)
 3042         """
 3043         self.verify("$getVar('bogus',  1234)",
 3044                     "1234")
 3045 
 3046     def test5(self):
 3047         """$getVar('$bogus', 1234)
 3048         """
 3049         self.verify("$getVar('$bogus',  1234)",
 3050                     "1234")
 3051 
 3052     def test6(self):
 3053         """$getVar('$') raises ValueError
 3054         """
 3055         with self.assertRaises(ValueError):
 3056             self.verify("$getVar('$')", "never get here")
 3057 
 3058 
 3059 class MiscComplexSyntax(OutputTest):
 3060     def test1(self):
 3061         """Complex use of {},[] and () in a #set expression
 3062         ----
 3063         #set $c = {'A':0}[{}.get('a', {'a' : 'A'}['a'])]
 3064         $c
 3065         """
 3066         self.verify("#set $c = {'A':0}[{}.get('a', {'a' : 'A'}['a'])]\n$c",
 3067                     "0")
 3068 
 3069 
 3070 class CGI(OutputTest):
 3071     """CGI scripts with(out) the CGI environment and with(out) GET variables.
 3072     """
 3073     convertEOLs = False
 3074 
 3075     def _beginCGI(self):
 3076         os.environ['REQUEST_METHOD'] = "GET"
 3077 
 3078     def _endCGI(self):
 3079         try:
 3080             del os.environ['REQUEST_METHOD']
 3081         except KeyError:
 3082             pass
 3083     _guaranteeNoCGI = _endCGI
 3084 
 3085     def test1(self):
 3086         """A regular template."""
 3087         self._guaranteeNoCGI()
 3088         source = "#extends Cheetah.Tools.CGITemplate\n" + \
 3089                  "#implements respond\n" + \
 3090                  "$cgiHeaders#slurp\n" + \
 3091                  "Hello, world!"
 3092         self.verify(source, "Hello, world!")
 3093 
 3094     def test2(self):
 3095         """A CGI script."""
 3096         self._beginCGI()
 3097         source = "#extends Cheetah.Tools.CGITemplate\n" + \
 3098                  "#implements respond\n" + \
 3099                  "$cgiHeaders#slurp\n" + \
 3100                  "Hello, world!"
 3101         self.verify(source, "Content-type: text/html\n\nHello, world!")
 3102         self._endCGI()
 3103 
 3104     def test3(self):
 3105         """A (pseudo) Webware servlet.
 3106 
 3107            This uses the Python syntax escape to set
 3108            self._CHEETAH__isControlledByWebKit.
 3109            We could instead do
 3110            '#silent self._CHEETAH__isControlledByWebKit = True',
 3111            taking advantage of the fact that it will compile unchanged as long
 3112            as there's no '$' in the statement.  (It won't compile with an '$'
 3113            because that would convert to a function call, and you can't assign
 3114            to a function call.)  Because this isn't really being called from
 3115            Webware, we'd better not use any Webware services!  Likewise, we'd
 3116            better not call $cgiImport() because it would be misled.
 3117         """
 3118         self._beginCGI()
 3119         source = "#extends Cheetah.Tools.CGITemplate\n" + \
 3120                  "#implements respond\n" + \
 3121                  "<% self._CHEETAH__isControlledByWebKit = True %>#slurp\n" + \
 3122                  "$cgiHeaders#slurp\n" + \
 3123                  "Hello, world!"
 3124         self.verify(source, "Hello, world!")
 3125         self._endCGI()
 3126 
 3127     def test4(self):
 3128         """A CGI script with a GET variable."""
 3129         self._beginCGI()
 3130         os.environ['QUERY_STRING'] = "cgiWhat=world"
 3131         source = "#extends Cheetah.Tools.CGITemplate\n" + \
 3132                  "#implements respond\n" + \
 3133                  "$cgiHeaders#slurp\n" + \
 3134                  "#silent $webInput(['cgiWhat'])##slurp\n" + \
 3135                  "Hello, $cgiWhat!"
 3136         self.verify(source,
 3137                     "Content-type: text/html\n\nHello, world!")
 3138         del os.environ['QUERY_STRING']
 3139         self._endCGI()
 3140 
 3141 
 3142 class WhitespaceAfterDirectiveTokens(OutputTest):
 3143     def _getCompilerSettings(self):
 3144         return {'allowWhitespaceAfterDirectiveStartToken': True}
 3145 
 3146     def test1(self):
 3147         self.verify("# for i in range(10): $i",
 3148                     "0123456789")
 3149         self.verify("# for i in range(10)\n$i# end for",
 3150                     "0123456789")
 3151         self.verify("# for i in range(10)#$i#end for",
 3152                     "0123456789")
 3153 
 3154 
 3155 class DefmacroDirective(OutputTest):
 3156     def _getCompilerSettings(self):
 3157         def aMacro(src):
 3158             return '$aStr'
 3159 
 3160         return {'macroDirectives': {'aMacro': aMacro}}
 3161 
 3162     def test1(self):
 3163         self.verify("""\
 3164 #defmacro inc: #set @src +=1
 3165 #set i = 1
 3166 #inc: $i
 3167 $i""",
 3168                     "2")
 3169 
 3170         self.verify("""\
 3171 #defmacro test
 3172 #for i in range(10): @src
 3173 #end defmacro
 3174 #test: $i-foo#slurp
 3175 #for i in range(3): $i""",
 3176                     "0-foo1-foo2-foo3-foo4-foo5-foo6-foo7-foo8-foo9-foo012")
 3177 
 3178         self.verify("""\
 3179 #defmacro test
 3180 #for i in range(10): @src
 3181 #end defmacro
 3182 #test: $i-foo
 3183 #for i in range(3): $i""",
 3184                     "0-foo\n1-foo\n2-foo\n3-foo\n4-foo\n5-foo\n"
 3185                     "6-foo\n7-foo\n8-foo\n9-foo\n012")
 3186 
 3187         self.verify("""\
 3188 #defmacro test: #for i in range(10): @src
 3189 #test: $i-foo#slurp
 3190 -#for i in range(3): $i""",
 3191                     "0-foo1-foo2-foo3-foo4-foo5-foo6-foo7-foo8-foo9-foo-012")
 3192 
 3193         self.verify("""\
 3194 #defmacro test##for i in range(10): @src#end defmacro##slurp
 3195 #test: $i-foo#slurp
 3196 -#for i in range(3): $i""",
 3197                     "0-foo1-foo2-foo3-foo4-foo5-foo6-foo7-foo8-foo9-foo-012")
 3198 
 3199         self.verify("""\
 3200 #defmacro testFoo: nothing
 3201 #defmacro test(foo=1234): #for i in range(10): @src
 3202 #test foo=234: $i-foo#slurp
 3203 -#for i in range(3): $i""",
 3204                     "0-foo1-foo2-foo3-foo4-foo5-foo6-foo7-foo8-foo9-foo-012")
 3205 
 3206         self.verify("""\
 3207 #defmacro testFoo: nothing
 3208 #defmacro test(foo=1234): #for i in range(10): @src@foo
 3209 #test foo='-foo'#$i#end test#-#for i in range(3): $i""",
 3210                     "0-foo1-foo2-foo3-foo4-foo5-foo6-foo7-foo8-foo9-foo-012")
 3211 
 3212         self.verify("""\
 3213 #defmacro testFoo: nothing
 3214 #defmacro test(foo=1234): #for i in range(10): @src.strip()@foo
 3215 #test foo='-foo': $i
 3216 -#for i in range(3): $i""",
 3217                     "0-foo1-foo2-foo3-foo4-foo5-foo6-foo7-foo8-foo9-foo-012")
 3218 
 3219     def test2(self):
 3220         self.verify("#aMacro: foo",
 3221                     "blarg")
 3222         self.verify("#defmacro nested: @macros.aMacro(@src)\n#nested: foo",
 3223                     "blarg")
 3224 
 3225 
 3226 class Indenter(OutputTest):
 3227     convertEOLs = False
 3228 
 3229     source = """
 3230 public class X
 3231 {
 3232     #for $method in $methods
 3233         $getMethod($method)
 3234 
 3235     #end for
 3236 }
 3237 //end of class
 3238 
 3239 #def getMethod($method)
 3240     #indent ++
 3241     public $getType($method) ${method.Name}($getParams($method.Params));
 3242     #indent --
 3243 #end def
 3244 
 3245 #def getParams($params)
 3246     #indent off
 3247 
 3248     #for $counter in $range($len($params))
 3249         #if $counter == len($params) - 1
 3250                        $params[$counter]#slurp
 3251         #else:
 3252                        $params[$counter],
 3253         #end if
 3254     #end for
 3255     #indent on
 3256 #end def
 3257 
 3258 #def getType($method)
 3259     #indent push
 3260     #indent=0
 3261     #if $method.Type == "VT_VOID"
 3262         void#slurp
 3263     #elif $method.Type == "VT_INT"
 3264         int#slurp
 3265     #elif $method.Type == "VT_VARIANT"
 3266         Object#slurp
 3267     #end if
 3268     #indent pop
 3269 #end def
 3270 """
 3271 
 3272     control = """
 3273 public class X
 3274 {
 3275     public void Foo(
 3276                        _input,
 3277                        _output);
 3278 
 3279 
 3280     public int Bar(
 3281                        _str1,
 3282                        str2,
 3283                        _str3);
 3284 
 3285 
 3286     public Object Add(
 3287                        value1,
 3288                        value);
 3289 
 3290 
 3291 }
 3292 //end of class
 3293 
 3294 
 3295 
 3296 """
 3297 
 3298     def _getCompilerSettings(self):
 3299         return {'useFilterArgsInPlaceholders': True}
 3300 
 3301     def searchList(self):    # Inside Indenter class.
 3302         class Method:
 3303             def __init__(self, _name, _type, *_params):
 3304                 self.Name = _name
 3305                 self.Type = _type
 3306                 self.Params = _params
 3307         methods = [Method("Foo", "VT_VOID", "_input", "_output"),
 3308                    Method("Bar", "VT_INT", "_str1", "str2", "_str3"),
 3309                    Method("Add", "VT_VARIANT", "value1", "value")]
 3310         return [{"methods": methods}]
 3311 
 3312     def test1(self):    # Inside Indenter class.
 3313         self.verify(self.source, self.control)
 3314 
 3315 
 3316 ##################################################
 3317 # CREATE CONVERTED EOL VERSIONS OF THE TEST CASES
 3318 
 3319 if OutputTest._useNewStyleCompilation:
 3320     extraCompileKwArgsForDiffBaseclass = {'baseclass': dict}
 3321 else:
 3322     extraCompileKwArgsForDiffBaseclass = {'baseclass': object}
 3323 
 3324 
 3325 def install_eols():
 3326     klasses = [v for v in globals().values()
 3327                if isinstance(v, type) and issubclass(v, unittest.TestCase)]
 3328     for klass in klasses:
 3329         name = klass.__name__
 3330         if hasattr(klass, 'convertEOLs') and klass.convertEOLs:
 3331             win32Src = r"class %(name)s_Win32EOL(%(name)s): " \
 3332                        r"_EOLreplacement = '\r\n'" % locals()
 3333             macSrc = r"class %(name)s_MacEOL(%(name)s): " \
 3334                      r"_EOLreplacement = '\r'" % locals()
 3335             exec(win32Src, globals())
 3336             exec(macSrc, globals())
 3337 
 3338         src = r"class %(name)s_DiffBaseClass(%(name)s): " % locals()
 3339         src += " _extraCompileKwArgs = extraCompileKwArgsForDiffBaseclass"
 3340         exec(src, globals())
 3341 
 3342         del name
 3343         del klass
 3344 
 3345 ##################################################
 3346 # if run from the command line ##
 3347 
 3348 
 3349 if __name__ == '__main__':
 3350     install_eols()
 3351     unittest.main()