How to use verify method in pact-foundation-pact

Best JavaScript code snippet using pact-foundation-pact

SyntaxAndOutput.py

Source:SyntaxAndOutput.py Github

copy

Full Screen

...125 #_useNewStyleCompilation = False126 _extraCompileKwArgs = None127 def searchList(self):128 return self._searchList129 def verify(self, input, expectedOutput,130 inputEncoding=None,131 outputEncoding=None,132 convertEOLs=Unspecified):133 if self._EOLreplacement:134 if convertEOLs is Unspecified:135 convertEOLs = self.convertEOLs136 if convertEOLs:137 input = input.replace('\n', self._EOLreplacement)138 expectedOutput = expectedOutput.replace('\n', self._EOLreplacement)139 self._input = input140 if self._useNewStyleCompilation:141 extraKwArgs = self._extraCompileKwArgs or {}142 143 templateClass = Template.compile(144 source=input,145 compilerSettings=self._getCompilerSettings(),146 keepRefToGeneratedCode=True,147 **extraKwArgs148 )149 moduleCode = templateClass._CHEETAH_generatedModuleCode150 self.template = templateObj = templateClass(searchList=self.searchList())151 else:152 self.template = templateObj = Template(153 input,154 searchList=self.searchList(),155 compilerSettings=self._getCompilerSettings(),156 )157 moduleCode = templateObj._CHEETAH_generatedModuleCode158 if self.DEBUGLEV >= 1:159 print moduleCode160 try:161 try:162 output = templateObj.respond() # rather than __str__, because of unicode163 if outputEncoding:164 output = output.decode(outputEncoding)165 assert output==expectedOutput, self._outputMismatchReport(output, expectedOutput)166 except:167 #print >>sys.stderr, moduleCode168 raise169 finally:170 templateObj.shutdown()171 def _getCompilerSettings(self):172 return {}173 174 def _outputMismatchReport(self, output, expectedOutput):175 if self._debugEOLReplacement and self._EOLreplacement:176 EOLrepl = self._EOLreplacement177 marker = '*EOL*'178 return self.report % {'template': self._input.replace(EOLrepl,marker),179 'expected': expectedOutput.replace(EOLrepl,marker),180 'actual': output.replace(EOLrepl,marker),181 'end': '(end)'}182 else:183 return self.report % {'template': self._input,184 'expected': expectedOutput,185 'actual': output,186 'end': '(end)'}187 188 def genClassCode(self):189 if hasattr(self, 'template'):190 return self.template.generatedClassCode()191 def genModuleCode(self):192 if hasattr(self, 'template'):193 return self.template.generatedModuleCode()194##################################################195## TEST CASE CLASSES196class EmptyTemplate(OutputTest):197 convertEOLs = False198 def test1(self):199 """an empty string for the template"""200 201 warnings.filterwarnings('error',202 'You supplied an empty string for the source!',203 UserWarning)204 try:205 self.verify("", "")206 except UserWarning:207 pass208 else:209 self.fail("Should warn about empty source strings.")210 211 try:212 self.verify("#implements foo", "")213 except NotImplementedError:214 pass215 else:216 self.fail("This should barf about respond() not being implemented.")217 self.verify("#implements respond", "")218 self.verify("#implements respond(foo=1234)", "")219class Backslashes(OutputTest):220 convertEOLs = False221 def setUp(self):222 fp = open('backslashes.txt','w')223 fp.write(r'\ #LogFormat "%h %l %u %t \"%r\" %>s %b"' + '\n\n\n\n\n\n\n')224 fp.flush()225 fp.close226 227 def tearDown(self):228 if os.path.exists('backslashes.txt'):229 os.remove('backslashes.txt')230 231 def test1(self):232 """ a single \\ using rawstrings"""233 self.verify(r"\ ",234 r"\ ")235 def test2(self):236 """ a single \\ using rawstrings and lots of lines"""237 self.verify(r"\ " + "\n\n\n\n\n\n\n\n\n",238 r"\ " + "\n\n\n\n\n\n\n\n\n")239 def test3(self):240 """ a single \\ without using rawstrings"""241 self.verify("\ \ ",242 "\ \ ")243 def test4(self):244 """ single line from an apache conf file"""245 self.verify(r'#LogFormat "%h %l %u %t \"%r\" %>s %b"',246 r'#LogFormat "%h %l %u %t \"%r\" %>s %b"')247 def test5(self):248 """ single line from an apache conf file with many NEWLINES249 The NEWLINES are used to make sure that MethodCompiler.commitStrConst()250 is handling long and short strings in the same fashion. It uses251 triple-quotes for strings with lots of \\n in them and repr(theStr) for252 shorter strings with only a few newlines."""253 254 self.verify(r'#LogFormat "%h %l %u %t \"%r\" %>s %b"' + '\n\n\n\n\n\n\n',255 r'#LogFormat "%h %l %u %t \"%r\" %>s %b"' + '\n\n\n\n\n\n\n')256 def test6(self):257 """ test backslash handling in an included file"""258 self.verify(r'#include "backslashes.txt"',259 r'\ #LogFormat "%h %l %u %t \"%r\" %>s %b"' + '\n\n\n\n\n\n\n')260 def test7(self):261 """ a single \\ without using rawstrings plus many NEWLINES"""262 self.verify("\ \ " + "\n\n\n\n\n\n\n\n\n",263 "\ \ " + "\n\n\n\n\n\n\n\n\n")264 def test8(self):265 """ single line from an apache conf file with single quotes and many NEWLINES 266 """267 268 self.verify(r"""#LogFormat '%h %l %u %t \"%r\" %>s %b'""" + '\n\n\n\n\n\n\n',269 r"""#LogFormat '%h %l %u %t \"%r\" %>s %b'""" + '\n\n\n\n\n\n\n')270 271class NonTokens(OutputTest):272 def test1(self):273 """dollar signs not in Cheetah $vars"""274 self.verify("$ $$ $5 $. $ test",275 "$ $$ $5 $. $ test")276 def test2(self):277 """hash not in #directives"""278 self.verify("# \# #5 ",279 "# # #5 ")280 def test3(self):281 """escapted comments"""282 self.verify(" \##escaped comment ",283 " ##escaped comment ")284 def test4(self):285 """escapted multi-line comments"""286 self.verify(" \#*escaped comment \n*# ",287 " #*escaped comment \n*# ")288 def test5(self):289 """1 dollar sign"""290 self.verify("$",291 "$")292 def _X_test6(self):293 """1 dollar sign followed by hash"""294 self.verify("\n$#\n",295 "\n$#\n")296 def test6(self):297 """1 dollar sign followed by EOL Slurp Token"""298 if DEFAULT_COMPILER_SETTINGS['EOLSlurpToken']:299 self.verify("\n$%s\n"%DEFAULT_COMPILER_SETTINGS['EOLSlurpToken'],300 "\n$")301 else:302 self.verify("\n$#\n",303 "\n$#\n")304 305class Comments_SingleLine(OutputTest):306 def test1(self):307 """## followed by WS"""308 self.verify("## ",309 "")310 def test2(self):311 """## followed by NEWLINE"""312 self.verify("##\n",313 "")314 def test3(self):315 """## followed by text then NEWLINE"""316 self.verify("## oeuao aoe uaoe \n",317 "")318 def test4(self):319 """## gobbles leading WS"""320 self.verify(" ## oeuao aoe uaoe \n",321 "")322 def test5(self):323 """## followed by text then NEWLINE, + leading WS"""324 self.verify(" ## oeuao aoe uaoe \n",325 "")326 def test6(self):327 """## followed by EOF"""328 self.verify("##",329 "")330 331 def test7(self):332 """## followed by EOF with leading WS"""333 self.verify(" ##",334 "")335 336 def test8(self):337 """## gobble line338 with text on previous and following lines"""339 self.verify("line1\n ## aoeu 1234 \nline2",340 "line1\nline2")341 def test9(self):342 """## don't gobble line343 with text on previous and following lines"""344 self.verify("line1\n 12 ## aoeu 1234 \nline2",345 "line1\n 12 \nline2")346 def test10(self):347 """## containing $placeholders348 """349 self.verify("##$a$b $c($d)",350 "")351 def test11(self):352 """## containing #for directive353 """354 self.verify("##for $i in range(15)",355 "")356class Comments_MultiLine_NoGobble(OutputTest):357 """358 Multiline comments used to not gobble whitespace. They do now, but this can359 be turned off with a compilerSetting 360 """361 def _getCompilerSettings(self):362 return {'gobbleWhitespaceAroundMultiLineComments':False}363 def test1(self):364 """#* *# followed by WS365 Shouldn't gobble WS366 """367 self.verify("#* blarg *# ",368 " ")369 370 def test2(self):371 """#* *# preceded and followed by WS372 Shouldn't gobble WS373 """374 self.verify(" #* blarg *# ",375 " ")376 377 def test3(self):378 """#* *# followed by WS, with NEWLINE379 Shouldn't gobble WS380 """381 self.verify("#* \nblarg\n *# ",382 " ")383 384 def test4(self):385 """#* *# preceded and followed by WS, with NEWLINE386 Shouldn't gobble WS387 """388 self.verify(" #* \nblarg\n *# ",389 " ")390class Comments_MultiLine(OutputTest):391 """392 Note: Multiline comments don't gobble whitespace!393 """394 395 def test1(self):396 """#* *# followed by WS397 Should gobble WS398 """399 self.verify("#* blarg *# ",400 "")401 402 def test2(self):403 """#* *# preceded and followed by WS404 Should gobble WS405 """406 self.verify(" #* blarg *# ",407 "")408 409 def test3(self):410 """#* *# followed by WS, with NEWLINE411 Shouldn't gobble WS412 """413 self.verify("#* \nblarg\n *# ",414 "")415 416 def test4(self):417 """#* *# preceded and followed by WS, with NEWLINE418 Shouldn't gobble WS419 """420 self.verify(" #* \nblarg\n *# ",421 "")422 def test5(self):423 """#* *# containing nothing 424 """425 self.verify("#**#",426 "")427 428 def test6(self):429 """#* *# containing only NEWLINES430 """431 self.verify(" #*\n\n\n\n\n\n\n\n*# ",432 "")433 def test7(self):434 """#* *# containing $placeholders435 """436 self.verify("#* $var $var(1234*$c) *#",437 "")438 439 def test8(self):440 """#* *# containing #for directive441 """442 self.verify("#* #for $i in range(15) *#",443 "")444 def test9(self):445 """ text around #* *# containing #for directive446 """447 self.verify("foo\nfoo bar #* #for $i in range(15) *# foo\n",448 "foo\nfoo bar foo\n")449 def test9(self):450 """ text around #* *# containing #for directive and trailing whitespace451 which should be gobbled452 """453 self.verify("foo\nfoo bar #* #for $i in range(15) *# \ntest",454 "foo\nfoo bar \ntest")455 def test10(self):456 """ text around #* *# containing #for directive and newlines: trailing whitespace457 which should be gobbled.458 """459 self.verify("foo\nfoo bar #* \n\n#for $i in range(15) \n\n*# \ntest",460 "foo\nfoo bar \ntest")461class Placeholders(OutputTest):462 def test1(self):463 """1 placeholder"""464 self.verify("$aStr", "blarg")465 466 def test2(self):467 """2 placeholders"""468 self.verify("$aStr $anInt", "blarg 1")469 def test3(self):470 """2 placeholders, back-to-back"""471 self.verify("$aStr$anInt", "blarg1")472 def test4(self):473 """1 placeholder enclosed in ()"""474 self.verify("$(aStr)", "blarg")475 476 def test5(self):477 """1 placeholder enclosed in {}"""478 self.verify("${aStr}", "blarg")479 def test6(self):480 """1 placeholder enclosed in []"""481 self.verify("$[aStr]", "blarg")482 def test7(self):483 """1 placeholder enclosed in () + WS484 Test to make sure that $(<WS><identifier>.. matches485 """486 self.verify("$( aStr )", "blarg")487 def test8(self):488 """1 placeholder enclosed in {} + WS"""489 self.verify("${ aStr }", "blarg")490 def test9(self):491 """1 placeholder enclosed in [] + WS"""492 self.verify("$[ aStr ]", "blarg")493 def test10(self):494 """1 placeholder enclosed in () + WS + * cache495 Test to make sure that $*(<WS><identifier>.. matches496 """497 self.verify("$*( aStr )", "blarg")498 def test11(self):499 """1 placeholder enclosed in {} + WS + *cache"""500 self.verify("$*{ aStr }", "blarg")501 def test12(self):502 """1 placeholder enclosed in [] + WS + *cache"""503 self.verify("$*[ aStr ]", "blarg")504 def test13(self):505 """1 placeholder enclosed in {} + WS + *<int>*cache"""506 self.verify("$*5*{ aStr }", "blarg")507 def test14(self):508 """1 placeholder enclosed in [] + WS + *<int>*cache"""509 self.verify("$*5*[ aStr ]", "blarg")510 def test15(self):511 """1 placeholder enclosed in {} + WS + *<float>*cache"""512 self.verify("$*0.5d*{ aStr }", "blarg")513 def test16(self):514 """1 placeholder enclosed in [] + WS + *<float>*cache"""515 self.verify("$*.5*[ aStr ]", "blarg")516 def test17(self):517 """1 placeholder + *<int>*cache"""518 self.verify("$*5*aStr", "blarg")519 def test18(self):520 """1 placeholder *<float>*cache"""521 self.verify("$*0.5h*aStr", "blarg")522 def test19(self):523 """1 placeholder surrounded by single quotes and multiple newlines"""524 self.verify("""'\n\n\n\n'$aStr'\n\n\n\n'""",525 """'\n\n\n\n'blarg'\n\n\n\n'""")526 def test20(self):527 """silent mode $!placeholders """528 self.verify("$!aStr$!nonExistant$!*nonExistant$!{nonExistant}", "blarg")529 try:530 self.verify("$!aStr$nonExistant",531 "blarg")532 except NotFound:533 pass534 else:535 self.fail('should raise NotFound exception')536 def test21(self):537 """Make sure that $*caching is actually working"""538 namesStr = 'You Me Them Everyone'539 names = namesStr.split()540 tmpl = Template.compile('#for name in $names: $name ', baseclass=dict)541 assert str(tmpl({'names':names})).strip()==namesStr542 tmpl = tmpl.subclass('#for name in $names: $*name ')543 assert str(tmpl({'names':names}))=='You '*len(names)544 tmpl = tmpl.subclass('#for name in $names: $*1*name ')545 assert str(tmpl({'names':names}))=='You '*len(names)546 tmpl = tmpl.subclass('#for name in $names: $*1*(name) ')547 assert str(tmpl({'names':names}))=='You '*len(names)548 if versionTuple > (2,2):549 tmpl = tmpl.subclass('#for name in $names: $*1*(name) ')550 assert str(tmpl(names=names))=='You '*len(names)551class Placeholders_Vals(OutputTest):552 convertEOLs = False553 def test1(self):554 """string"""555 self.verify("$aStr", "blarg")556 def test2(self):557 """string - with whitespace"""558 self.verify(" $aStr ", " blarg ")559 def test3(self):560 """empty string - with whitespace"""561 self.verify("$emptyString", "")562 def test4(self):563 """int"""564 self.verify("$anInt", "1")565 def test5(self):566 """float"""567 self.verify("$aFloat", "1.5")568 def test6(self):569 """list"""570 self.verify("$aList", "['item0', 'item1', 'item2']")571 def test7(self):572 """None573 The default output filter is ReplaceNone.574 """575 self.verify("$none", "")576 def test8(self):577 """True, False578 """579 self.verify("$True $False", "%s %s"%(repr(True), repr(False)))580 def test9(self):581 """$_582 """583 self.verify("$_('foo')", "Translated: foo")584class PlaceholderStrings(OutputTest):585 def test1(self):586 """some c'text $placeholder text' strings"""587 self.verify("$str(c'$aStr')", "blarg")588 def test2(self):589 """some c'text $placeholder text' strings"""590 self.verify("$str(c'$aStr.upper')", "BLARG")591 def test3(self):592 """some c'text $placeholder text' strings"""593 self.verify("$str(c'$(aStr.upper.replace(c\"A$str()\",\"\"))')", "BLRG")594 def test4(self):595 """some c'text $placeholder text' strings"""596 self.verify("#echo $str(c'$(aStr.upper)')", "BLARG")597 def test5(self):598 """some c'text $placeholder text' strings"""599 self.verify("#if 1 then $str(c'$(aStr.upper)') else 0", "BLARG")600 def test6(self):601 """some c'text $placeholder text' strings"""602 self.verify("#if 1\n$str(c'$(aStr.upper)')#slurp\n#else\n0#end if", "BLARG")603 def test7(self):604 """some c'text $placeholder text' strings"""605 self.verify("#def foo(arg=c'$(\"BLARG\")')\n"606 "$arg#slurp\n"607 "#end def\n"608 "$foo()$foo(c'$anInt')#slurp",609 610 "BLARG1")611class UnicodeStrings(OutputTest):612 def test1(self):613 """unicode data in placeholder614 """615 #self.verify(u"$unicodeData", defaultTestNameSpace['unicodeData'], outputEncoding='utf8')616 self.verify(u"$unicodeData", defaultTestNameSpace['unicodeData'])617 def test2(self):618 """unicode data in body619 """620 self.verify(u"aoeu12345\u1234", u"aoeu12345\u1234")621 #self.verify(u"#encoding utf8#aoeu12345\u1234", u"aoeu12345\u1234")622class EncodingDirective(OutputTest):623 def test1(self):624 """basic #encoding """625 self.verify("#encoding utf-8\n1234",626 "1234")627 def test2(self):628 """basic #encoding """629 self.verify("#encoding ascii\n1234",630 "1234")631 def test3(self):632 """basic #encoding """633 self.verify("#encoding utf-8\n\xe1\x88\xb4",634 u'\u1234', outputEncoding='utf8')635 def test4(self):636 """basic #encoding """637 self.verify("#encoding ascii\n\xe1\x88\xb4",638 "\xe1\x88\xb4")639 def test5(self):640 """basic #encoding """641 self.verify("#encoding latin-1\nAndr\202",642 u'Andr\202', outputEncoding='latin-1')643class UnicodeDirective(OutputTest):644 def test1(self):645 """basic #unicode """646 self.verify("#unicode utf-8\n1234",647 u"1234")648 649 self.verify("#unicode ascii\n1234",650 u"1234")651 self.verify("#unicode latin-1\n1234",652 u"1234")653 self.verify("#unicode latin-1\n1234ü",654 u"1234ü")655 self.verify("#unicode: latin-1\n1234ü",656 u"1234ü")657 self.verify("# unicode : latin-1\n1234ü",658 u"1234ü")659 self.verify(u"#unicode latin-1\n1234ü",660 u"1234ü")661 self.verify("#encoding latin-1\n1234ü",662 "1234ü")663class Placeholders_Esc(OutputTest):664 convertEOLs = False665 def test1(self):666 """1 escaped placeholder"""667 self.verify("\$var",668 "$var")669 670 def test2(self):671 """2 escaped placeholders"""672 self.verify("\$var \$_",673 "$var $_")674 def test3(self):675 """2 escaped placeholders - back to back"""676 self.verify("\$var\$_",677 "$var$_")678 def test4(self):679 """2 escaped placeholders - nested"""680 self.verify("\$var(\$_)",681 "$var($_)")682 def test5(self):683 """2 escaped placeholders - nested and enclosed"""684 self.verify("\$(var(\$_)",685 "$(var($_)")686class Placeholders_Calls(OutputTest):687 def test1(self):688 """func placeholder - no ()"""689 self.verify("$aFunc",690 "Scooby")691 def test2(self):692 """func placeholder - with ()"""693 self.verify("$aFunc()",694 "Scooby")695 def test3(self):696 r"""func placeholder - with (\n\n)"""697 self.verify("$aFunc(\n\n)",698 "Scooby", convertEOLs=False)699 def test4(self):700 r"""func placeholder - with (\n\n) and $() enclosure"""701 self.verify("$(aFunc(\n\n))",702 "Scooby", convertEOLs=False)703 def test5(self):704 r"""func placeholder - with (\n\n) and ${} enclosure"""705 self.verify("${aFunc(\n\n)}",706 "Scooby", convertEOLs=False)707 708 def test6(self):709 """func placeholder - with (int)"""710 self.verify("$aFunc(1234)",711 "1234")712 def test7(self):713 r"""func placeholder - with (\nint\n)"""714 self.verify("$aFunc(\n1234\n)",715 "1234", convertEOLs=False)716 def test8(self):717 """func placeholder - with (string)"""718 self.verify("$aFunc('aoeu')",719 "aoeu")720 721 def test9(self):722 """func placeholder - with ('''string''')"""723 self.verify("$aFunc('''aoeu''')",724 "aoeu")725 def test10(self):726 r"""func placeholder - with ('''\nstring\n''')"""727 self.verify("$aFunc('''\naoeu\n''')",728 "\naoeu\n")729 def test11(self):730 r"""func placeholder - with ('''\nstring'\n''')"""731 self.verify("$aFunc('''\naoeu'\n''')",732 "\naoeu'\n")733 def test12(self):734 r'''func placeholder - with ("""\nstring\n""")'''735 self.verify('$aFunc("""\naoeu\n""")',736 "\naoeu\n")737 def test13(self):738 """func placeholder - with (string*int)"""739 self.verify("$aFunc('aoeu'*2)",740 "aoeuaoeu")741 def test14(self):742 """func placeholder - with (int*int)"""743 self.verify("$aFunc(2*2)",744 "4")745 def test15(self):746 """func placeholder - with (int*float)"""747 self.verify("$aFunc(2*2.0)",748 "4.0")749 def test16(self):750 r"""func placeholder - with (int\n*\nfloat)"""751 self.verify("$aFunc(2\n*\n2.0)",752 "4.0", convertEOLs=False)753 def test17(self):754 """func placeholder - with ($arg=float)"""755 self.verify("$aFunc($arg=4.0)",756 "4.0")757 def test18(self):758 """func placeholder - with (arg=float)"""759 self.verify("$aFunc(arg=4.0)",760 "4.0")761 def test19(self):762 """deeply nested argstring, no enclosure"""763 self.verify("$aFunc($arg=$aMeth($arg=$aFunc(1)))",764 "1")765 def test20(self):766 """deeply nested argstring, no enclosure + with WS"""767 self.verify("$aFunc( $arg = $aMeth( $arg = $aFunc( 1 ) ) )",768 "1")769 def test21(self):770 """deeply nested argstring, () enclosure + with WS"""771 self.verify("$(aFunc( $arg = $aMeth( $arg = $aFunc( 1 ) ) ) )",772 "1")773 774 def test22(self):775 """deeply nested argstring, {} enclosure + with WS"""776 self.verify("${aFunc( $arg = $aMeth( $arg = $aFunc( 1 ) ) ) }",777 "1")778 def test23(self):779 """deeply nested argstring, [] enclosure + with WS"""780 self.verify("$[aFunc( $arg = $aMeth( $arg = $aFunc( 1 ) ) ) ]",781 "1")782 def test24(self):783 """deeply nested argstring, () enclosure + *cache"""784 self.verify("$*(aFunc( $arg = $aMeth( $arg = $aFunc( 1 ) ) ) )",785 "1")786 def test25(self):787 """deeply nested argstring, () enclosure + *15*cache"""788 self.verify("$*15*(aFunc( $arg = $aMeth( $arg = $aFunc( 1 ) ) ) )",789 "1")790 def test26(self):791 """a function call with the Python None kw."""792 self.verify("$aFunc(None)",793 "")794class NameMapper(OutputTest):795 def test1(self):796 """autocalling"""797 self.verify("$aFunc! $aFunc().",798 "Scooby! Scooby.")799 def test2(self):800 """nested autocalling"""801 self.verify("$aFunc($aFunc).",802 "Scooby.")803 def test3(self):804 """list subscription"""805 self.verify("$aList[0]",806 "item0")807 def test4(self):808 """list slicing"""809 self.verify("$aList[:2]",810 "['item0', 'item1']")811 812 def test5(self):813 """list slicing and subcription combined"""814 self.verify("$aList[:2][0]",815 "item0")816 def test6(self):817 """dictionary access - NameMapper style"""818 self.verify("$aDict.one",819 "item1")820 821 def test7(self):822 """dictionary access - Python style"""823 self.verify("$aDict['one']",824 "item1")825 def test8(self):826 """dictionary access combined with autocalled string method"""827 self.verify("$aDict.one.upper",828 "ITEM1")829 def test9(self):830 """dictionary access combined with string method"""831 self.verify("$aDict.one.upper()",832 "ITEM1")833 def test10(self):834 """nested dictionary access - NameMapper style"""835 self.verify("$aDict.nestedDict.two",836 "nestedItem2")837 838 def test11(self):839 """nested dictionary access - Python style"""840 self.verify("$aDict['nestedDict']['two']",841 "nestedItem2")842 def test12(self):843 """nested dictionary access - alternating style"""844 self.verify("$aDict['nestedDict'].two",845 "nestedItem2")846 def test13(self):847 """nested dictionary access using method - alternating style"""848 self.verify("$aDict.get('nestedDict').two",849 "nestedItem2")850 def test14(self):851 """nested dictionary access - NameMapper style - followed by method"""852 self.verify("$aDict.nestedDict.two.upper",853 "NESTEDITEM2")854 def test15(self):855 """nested dictionary access - alternating style - followed by method"""856 self.verify("$aDict['nestedDict'].two.upper",857 "NESTEDITEM2")858 def test16(self):859 """nested dictionary access - NameMapper style - followed by method, then slice"""860 self.verify("$aDict.nestedDict.two.upper[:4]",861 "NEST")862 def test17(self):863 """nested dictionary access - Python style using a soft-coded key"""864 self.verify("$aDict[$anObj.meth('nestedDict')].two",865 "nestedItem2")866 def test18(self):867 """object method access"""868 self.verify("$anObj.meth1",869 "doo")870 def test19(self):871 """object method access, followed by complex slice"""872 self.verify("$anObj.meth1[0: ((4/4*2)*2)/$anObj.meth1(2) ]",873 "do")874 def test20(self):875 """object method access, followed by a very complex slice876 If it can pass this one, it's safe to say it works!!"""877 self.verify("$( anObj.meth1[0:\n (\n(4/4*2)*2)/$anObj.meth1(2)\n ] )",878 "do")879 def test21(self):880 """object method access with % in the default arg for the meth.881 This tests a bug that Jeff Johnson found and submitted a patch to SF882 for."""883 884 self.verify("$anObj.methWithPercentSignDefaultArg",885 "110%")886#class NameMapperDict(OutputTest):887#888# _searchList = [{"update": "Yabba dabba doo!"}]889#890# def test1(self):891# if NameMapper_C_VERSION:892# return # This feature is not in the C version yet.893# self.verify("$update", "Yabba dabba doo!")894#895class CacheDirective(OutputTest):896 897 def test1(self):898 r"""simple #cache """899 self.verify("#cache:$anInt",900 "1")901 def test2(self):902 r"""simple #cache + WS"""903 self.verify(" #cache \n$anInt#end cache",904 "1")905 def test3(self):906 r"""simple #cache ... #end cache"""907 self.verify("""#cache id='cache1', timer=150m908$anInt909#end cache910$aStr""",911 "1\nblarg")912 913 def test4(self):914 r"""2 #cache ... #end cache blocks"""915 self.verify("""#slurp916#def foo917#cache ID='cache1', timer=150m918$anInt919#end cache920#cache id='cache2', timer=15s921 #for $i in range(5)922$i#slurp923 #end for924#end cache925$aStr#slurp926#end def927$foo$foo$foo$foo$foo""",928 "1\n01234blarg"*5)929 def test5(self):930 r"""nested #cache blocks"""931 self.verify("""#slurp932#def foo 933#cache ID='cache1', timer=150m934$anInt935#cache id='cache2', timer=15s936 #for $i in range(5)937$i#slurp938 #end for939$*(6)#slurp940#end cache941#end cache942$aStr#slurp943#end def944$foo$foo$foo$foo$foo""",945 "1\n012346blarg"*5)946 947 def test6(self):948 r"""Make sure that partial directives don't match"""949 self.verify("#cache_foo",950 "#cache_foo")951 self.verify("#cached",952 "#cached")953class CallDirective(OutputTest):954 955 def test1(self):956 r"""simple #call """957 self.verify("#call int\n$anInt#end call",958 "1")959 # single line version960 self.verify("#call int: $anInt",961 "1")962 self.verify("#call int: 10\n$aStr",963 "10\nblarg")964 def test2(self):965 r"""simple #call + WS"""966 self.verify("#call int\n$anInt #end call",967 "1")968 def test3(self):969 r"""a longer #call"""970 self.verify('''\971#def meth(arg)972$arg.upper()#slurp973#end def974#call $meth975$(1234+1) foo#slurp976#end call''',977 "1235 FOO")978 def test4(self):979 r"""#call with keyword #args"""980 self.verify('''\981#def meth(arg1, arg2)982$arg1.upper() - $arg2.lower()#slurp983#end def984#call self.meth985#arg arg1986$(1234+1) foo#slurp987#arg arg2988UPPER#slurp989#end call''',990 "1235 FOO - upper")991 def test5(self):992 r"""#call with single-line keyword #args """993 self.verify('''\994#def meth(arg1, arg2)995$arg1.upper() - $arg2.lower()#slurp996#end def997#call self.meth998#arg arg1:$(1234+1) foo#slurp999#arg arg2:UPPER#slurp1000#end call''',1001 "1235 FOO - upper")1002 1003 def test6(self):1004 """#call with python kwargs and cheetah output for the 1s positional1005 arg"""1006 1007 self.verify('''\1008#def meth(arg1, arg2)1009$arg1.upper() - $arg2.lower()#slurp1010#end def1011#call self.meth arg2="UPPER"1012$(1234+1) foo#slurp1013#end call''',1014 "1235 FOO - upper")1015 def test7(self):1016 """#call with python kwargs and #args"""1017 self.verify('''\1018#def meth(arg1, arg2, arg3)1019$arg1.upper() - $arg2.lower() - $arg3#slurp1020#end def1021#call self.meth arg2="UPPER", arg3=9991022#arg arg1:$(1234+1) foo#slurp1023#end call''',1024 "1235 FOO - upper - 999")1025 1026 def test8(self):1027 """#call with python kwargs and #args, and using a function to get the1028 function that will be called"""1029 self.verify('''\1030#def meth(arg1, arg2, arg3)1031$arg1.upper() - $arg2.lower() - $arg3#slurp1032#end def1033#call getattr(self, "meth") arg2="UPPER", arg3=9991034#arg arg1:$(1234+1) foo#slurp1035#end call''',1036 "1235 FOO - upper - 999")1037 def test9(self):1038 """nested #call directives"""1039 self.verify('''\1040#def meth(arg1)1041$arg1#slurp1042#end def1043#def meth2(x,y)1044$x$y#slurp1045#end def1046##1047#call self.meth10481#slurp1049#call self.meth10502#slurp1051#call self.meth10523#slurp1053#end call 31054#set two = 21055#call self.meth2 y=c"$(10/$two)"1056#arg x10574#slurp1058#end call 41059#end call 21060#end call 1''',1061 "12345")1062class I18nDirective(OutputTest): 1063 def test1(self):1064 r"""simple #call """1065 self.verify("#i18n \n$anInt#end i18n",1066 "1")1067 1068 # single line version1069 self.verify("#i18n: $anInt",1070 "1")1071 self.verify("#i18n: 10\n$aStr",1072 "10\nblarg")1073class CaptureDirective(OutputTest):1074 def test1(self):1075 r"""simple #capture"""1076 self.verify('''\1077#capture cap11078$(1234+1) foo#slurp1079#end capture1080$cap1#slurp1081''',1082 "1235 foo")1083 def test2(self):1084 r"""slightly more complex #capture"""1085 self.verify('''\1086#def meth(arg)1087$arg.upper()#slurp1088#end def1089#capture cap11090$(1234+1) $anInt $meth("foo")#slurp1091#end capture1092$cap1#slurp1093''',1094 "1235 1 FOO")1095class SlurpDirective(OutputTest):1096 def test1(self):1097 r"""#slurp with 1 \n """1098 self.verify("#slurp\n",1099 "")1100 def test2(self):1101 r"""#slurp with 1 \n, leading whitespace1102 Should gobble"""1103 self.verify(" #slurp\n",1104 "")1105 1106 def test3(self):1107 r"""#slurp with 1 \n, leading content1108 Shouldn't gobble"""1109 self.verify(" 1234 #slurp\n",1110 " 1234 ")1111 1112 def test4(self):1113 r"""#slurp with WS then \n, leading content1114 Shouldn't gobble"""1115 self.verify(" 1234 #slurp \n",1116 " 1234 ")1117 def test5(self):1118 r"""#slurp with garbage chars then \n, leading content1119 Should eat the garbage"""1120 self.verify(" 1234 #slurp garbage \n",1121 " 1234 ")1122class EOLSlurpToken(OutputTest):1123 _EOLSlurpToken = DEFAULT_COMPILER_SETTINGS['EOLSlurpToken']1124 def test1(self):1125 r"""#slurp with 1 \n """1126 self.verify("%s\n"%self._EOLSlurpToken,1127 "")1128 def test2(self):1129 r"""#slurp with 1 \n, leading whitespace1130 Should gobble"""1131 self.verify(" %s\n"%self._EOLSlurpToken,1132 "")1133 def test3(self):1134 r"""#slurp with 1 \n, leading content1135 Shouldn't gobble"""1136 self.verify(" 1234 %s\n"%self._EOLSlurpToken,1137 " 1234 ")1138 1139 def test4(self):1140 r"""#slurp with WS then \n, leading content1141 Shouldn't gobble"""1142 self.verify(" 1234 %s \n"%self._EOLSlurpToken,1143 " 1234 ")1144 def test5(self):1145 r"""#slurp with garbage chars then \n, leading content1146 Should NOT eat the garbage"""1147 self.verify(" 1234 %s garbage \n"%self._EOLSlurpToken,1148 " 1234 %s garbage \n"%self._EOLSlurpToken)1149if not DEFAULT_COMPILER_SETTINGS['EOLSlurpToken']:1150 del EOLSlurpToken1151class RawDirective(OutputTest):1152 def test1(self):1153 """#raw till EOF"""1154 self.verify("#raw\n$aFunc().\n\n",1155 "$aFunc().\n\n")1156 def test2(self):1157 """#raw till #end raw"""1158 self.verify("#raw\n$aFunc().\n#end raw\n$anInt",1159 "$aFunc().\n1")1160 1161 def test3(self):1162 """#raw till #end raw gobble WS"""1163 self.verify(" #raw \n$aFunc().\n #end raw \n$anInt",1164 "$aFunc().\n1")1165 def test4(self):1166 """#raw till #end raw using explicit directive closure1167 Shouldn't gobble"""1168 self.verify(" #raw #\n$aFunc().\n #end raw #\n$anInt",1169 " \n$aFunc().\n\n1")1170 def test5(self):1171 """single-line short form #raw: """1172 self.verify("#raw: $aFunc().\n\n",1173 "$aFunc().\n\n")1174 self.verify("#raw: $aFunc().\n$anInt",1175 "$aFunc().\n1")1176class BreakpointDirective(OutputTest):1177 def test1(self):1178 """#breakpoint part way through source code"""1179 self.verify("$aFunc(2).\n#breakpoint\n$anInt",1180 "2.\n")1181 def test2(self):1182 """#breakpoint at BOF"""1183 self.verify("#breakpoint\n$anInt",1184 "")1185 def test3(self):1186 """#breakpoint at EOF"""1187 self.verify("$anInt\n#breakpoint",1188 "1\n")1189class StopDirective(OutputTest):1190 def test1(self):1191 """#stop part way through source code"""1192 self.verify("$aFunc(2).\n#stop\n$anInt",1193 "2.\n")1194 def test2(self):1195 """#stop at BOF"""1196 self.verify("#stop\n$anInt",1197 "")1198 def test3(self):1199 """#stop at EOF"""1200 self.verify("$anInt\n#stop",1201 "1\n")1202 def test4(self):1203 """#stop in pos test block"""1204 self.verify("""$anInt1205#if 11206inside the if block1207#stop1208#end if1209blarg""",1210 "1\ninside the if block\n")1211 def test5(self):1212 """#stop in neg test block"""1213 self.verify("""$anInt1214#if 01215inside the if block1216#stop1217#end if1218blarg""",1219 "1\nblarg")1220class ReturnDirective(OutputTest):1221 1222 def test1(self):1223 """#return'ing an int """1224 self.verify("""11225$str($test-6)122631227#def test1228#if 11229#return (3 *2) \1230 + 2 1231#else1232aoeuoaeu1233#end if1234#end def1235""",1236 "1\n2\n3\n")1237 def test2(self):1238 """#return'ing an string """1239 self.verify("""11240$str($test[1])124131242#def test1243#if 11244#return '123'1245#else1246aoeuoaeu1247#end if1248#end def1249""",1250 "1\n2\n3\n")1251 def test3(self):1252 """#return'ing an string AND streaming other output via the transaction"""1253 self.verify("""11254$str($test(trans=trans)[1])125531256#def test12571.51258#if 11259#return '123'1260#else1261aoeuoaeu1262#end if1263#end def1264""",1265 "1\n1.5\n2\n3\n")1266class YieldDirective(OutputTest):1267 convertEOLs = False1268 def test1(self):1269 """simple #yield """1270 1271 src1 = """#for i in range(10)\n#yield i\n#end for"""1272 src2 = """#for i in range(10)\n$i#slurp\n#yield\n#end for"""1273 src3 = ("#def iterator\n"1274 "#for i in range(10)\n#yield i\n#end for\n"1275 "#end def\n"1276 "#for i in $iterator\n$i#end for"1277 )1278 for src in (src1,src2,src3):1279 klass = Template.compile(src, keepRefToGeneratedCode=True)1280 #print klass._CHEETAH_generatedModuleCode1281 iter = klass().respond()1282 output = [str(i) for i in iter]1283 assert ''.join(output)=='0123456789'1284 #print ''.join(output)1285 # @@TR: need to expand this to cover error conditions etc.1286if versionTuple < (2,3):1287 del YieldDirective1288 1289class ForDirective(OutputTest):1290 def test1(self):1291 """#for loop with one local var"""1292 self.verify("#for $i in range(5)\n$i\n#end for",1293 "0\n1\n2\n3\n4\n")1294 self.verify("#for $i in range(5):\n$i\n#end for",1295 "0\n1\n2\n3\n4\n")1296 self.verify("#for $i in range(5): ##comment\n$i\n#end for",1297 "0\n1\n2\n3\n4\n")1298 self.verify("#for $i in range(5) ##comment\n$i\n#end for",1299 "0\n1\n2\n3\n4\n")1300 def test2(self):1301 """#for loop with WS in loop"""1302 self.verify("#for $i in range(5)\n$i \n#end for",1303 "0 \n1 \n2 \n3 \n4 \n")1304 1305 def test3(self):1306 """#for loop gobble WS"""1307 self.verify(" #for $i in range(5) \n$i \n #end for ",1308 "0 \n1 \n2 \n3 \n4 \n")1309 def test4(self):1310 """#for loop over list"""1311 self.verify("#for $i, $j in [(0,1),(2,3)]\n$i,$j\n#end for",1312 "0,1\n2,3\n")1313 1314 def test5(self):1315 """#for loop over list, with #slurp"""1316 self.verify("#for $i, $j in [(0,1),(2,3)]\n$i,$j#slurp\n#end for",1317 "0,12,3")1318 def test6(self):1319 """#for loop with explicit closures"""1320 self.verify("#for $i in range(5)#$i#end for#",1321 "01234")1322 def test7(self):1323 """#for loop with explicit closures and WS"""1324 self.verify(" #for $i in range(5)#$i#end for# ",1325 " 01234 ")1326 def test8(self):1327 """#for loop using another $var"""1328 self.verify(" #for $i in range($aFunc(5))#$i#end for# ",1329 " 01234 ")1330 def test9(self):1331 """test methods in for loops"""1332 self.verify("#for $func in $listOfLambdas\n$func($anInt)\n#end for",1333 "1\n1\n1\n")1334 def test10(self):1335 """#for loop over list, using methods of the items"""1336 self.verify("#for i, j in [('aa','bb'),('cc','dd')]\n$i.upper,$j.upper\n#end for",1337 "AA,BB\nCC,DD\n")1338 self.verify("#for $i, $j in [('aa','bb'),('cc','dd')]\n$i.upper,$j.upper\n#end for",1339 "AA,BB\nCC,DD\n")1340 def test11(self):1341 """#for loop over list, using ($i,$j) style target list"""1342 self.verify("#for (i, j) in [('aa','bb'),('cc','dd')]\n$i.upper,$j.upper\n#end for",1343 "AA,BB\nCC,DD\n")1344 self.verify("#for ($i, $j) in [('aa','bb'),('cc','dd')]\n$i.upper,$j.upper\n#end for",1345 "AA,BB\nCC,DD\n")1346 def test12(self):1347 """#for loop over list, using i, (j,k) style target list"""1348 self.verify("#for i, (j, k) in enumerate([('aa','bb'),('cc','dd')])\n$j.upper,$k.upper\n#end for",1349 "AA,BB\nCC,DD\n")1350 self.verify("#for $i, ($j, $k) in enumerate([('aa','bb'),('cc','dd')])\n$j.upper,$k.upper\n#end for",1351 "AA,BB\nCC,DD\n")1352 def test13(self):1353 """single line #for"""1354 self.verify("#for $i in range($aFunc(5)): $i",1355 "01234")1356 def test14(self):1357 """single line #for with 1 extra leading space"""1358 self.verify("#for $i in range($aFunc(5)): $i",1359 " 0 1 2 3 4")1360 def test15(self):1361 """2 times single line #for"""1362 self.verify("#for $i in range($aFunc(5)): $i#slurp\n"*2,1363 "01234"*2)1364 def test16(self):1365 """false single line #for """1366 self.verify("#for $i in range(5): \n$i\n#end for",1367 "0\n1\n2\n3\n4\n")1368if versionTuple < (2,3):1369 del ForDirective.test121370class RepeatDirective(OutputTest):1371 def test1(self):1372 """basic #repeat"""1373 self.verify("#repeat 3\n1\n#end repeat",1374 "1\n1\n1\n")1375 self.verify("#repeat 3: \n1\n#end repeat",1376 "1\n1\n1\n")1377 self.verify("#repeat 3 ##comment\n1\n#end repeat",1378 "1\n1\n1\n")1379 self.verify("#repeat 3: ##comment\n1\n#end repeat",1380 "1\n1\n1\n")1381 def test2(self):1382 """#repeat with numeric expression"""1383 self.verify("#repeat 3*3/3\n1\n#end repeat",1384 "1\n1\n1\n")1385 1386 def test3(self):1387 """#repeat with placeholder"""1388 self.verify("#repeat $numTwo\n1\n#end repeat",1389 "1\n1\n")1390 1391 def test4(self):1392 """#repeat with placeholder * num"""1393 self.verify("#repeat $numTwo*1\n1\n#end repeat",1394 "1\n1\n")1395 1396 def test5(self):1397 """#repeat with placeholder and WS"""1398 self.verify(" #repeat $numTwo \n1\n #end repeat ",1399 "1\n1\n")1400 def test6(self):1401 """single-line #repeat"""1402 self.verify("#repeat $numTwo: 1",1403 "11")1404 self.verify("#repeat $numTwo: 1\n"*2,1405 "1\n1\n"*2)1406 #false single-line1407 self.verify("#repeat 3: \n1\n#end repeat",1408 "1\n1\n1\n")1409class AttrDirective(OutputTest):1410 def test1(self):1411 """#attr with int"""1412 self.verify("#attr $test = 1234\n$test",1413 "1234")1414 def test2(self):1415 """#attr with string"""1416 self.verify("#attr $test = 'blarg'\n$test",1417 "blarg")1418 def test3(self):1419 """#attr with expression"""1420 self.verify("#attr $test = 'blarg'.upper()*2\n$test",1421 "BLARGBLARG")1422 def test4(self):1423 """#attr with string + WS1424 Should gobble"""1425 self.verify(" #attr $test = 'blarg' \n$test",1426 "blarg")1427 def test5(self):1428 """#attr with string + WS + leading text1429 Shouldn't gobble"""1430 self.verify(" -- #attr $test = 'blarg' \n$test",1431 " -- \nblarg")1432class DefDirective(OutputTest):1433 def test1(self):1434 """#def without argstring"""1435 self.verify("#def testMeth\n1234\n#end def\n$testMeth",1436 "1234\n")1437 self.verify("#def testMeth ## comment\n1234\n#end def\n$testMeth",1438 "1234\n")1439 self.verify("#def testMeth: ## comment\n1234\n#end def\n$testMeth",1440 "1234\n")1441 def test2(self):1442 """#def without argstring, gobble WS"""1443 self.verify(" #def testMeth \n1234\n #end def \n$testMeth",1444 "1234\n")1445 def test3(self):1446 """#def with argstring, gobble WS"""1447 self.verify(" #def testMeth($a=999) \n1234-$a\n #end def\n$testMeth",1448 "1234-999\n")1449 def test4(self):1450 """#def with argstring, gobble WS, string used in call"""1451 self.verify(" #def testMeth($a=999) \n1234-$a\n #end def\n$testMeth('ABC')",1452 "1234-ABC\n")1453 def test5(self):1454 """#def with argstring, gobble WS, list used in call"""1455 self.verify(" #def testMeth($a=999) \n1234-$a\n #end def\n$testMeth([1,2,3])",1456 "1234-[1, 2, 3]\n")1457 def test6(self):1458 """#def with 2 args, gobble WS, list used in call"""1459 self.verify(" #def testMeth($a, $b='default') \n1234-$a$b\n #end def\n$testMeth([1,2,3])",1460 "1234-[1, 2, 3]default\n")1461 def test7(self):1462 """#def with *args, gobble WS"""1463 self.verify(" #def testMeth($*args) \n1234-$args\n #end def\n$testMeth",1464 "1234-()\n")1465 def test8(self):1466 """#def with **KWs, gobble WS"""1467 self.verify(" #def testMeth($**KWs) \n1234-$KWs\n #end def\n$testMeth",1468 "1234-{}\n")1469 def test9(self):1470 """#def with *args + **KWs, gobble WS"""1471 self.verify(" #def testMeth($*args, $**KWs) \n1234-$args-$KWs\n #end def\n$testMeth",1472 "1234-()-{}\n")1473 def test10(self):1474 """#def with *args + **KWs, gobble WS"""1475 self.verify(1476 " #def testMeth($*args, $**KWs) \n1234-$args-$KWs.a\n #end def\n$testMeth(1,2, a=1)",1477 "1234-(1, 2)-1\n")1478 def test11(self):1479 """single line #def with extra WS"""1480 self.verify(1481 "#def testMeth: aoeuaoeu\n- $testMeth -",1482 "- aoeuaoeu -")1483 def test12(self):1484 """single line #def with extra WS and nested $placeholders"""1485 self.verify(1486 "#def testMeth: $anInt $aFunc(1234)\n- $testMeth -",1487 "- 1 1234 -")1488 def test13(self):1489 """single line #def escaped $placeholders"""1490 self.verify(1491 "#def testMeth: \$aFunc(\$anInt)\n- $testMeth -",1492 "- $aFunc($anInt) -")1493 def test14(self):1494 """single line #def 1 escaped $placeholders"""1495 self.verify(1496 "#def testMeth: \$aFunc($anInt)\n- $testMeth -",1497 "- $aFunc(1) -")1498 def test15(self):1499 """single line #def 1 escaped $placeholders + more WS"""1500 self.verify(1501 "#def testMeth : \$aFunc($anInt)\n- $testMeth -",1502 "- $aFunc(1) -")1503 def test16(self):1504 """multiline #def with $ on methodName"""1505 self.verify("#def $testMeth\n1234\n#end def\n$testMeth",1506 "1234\n")1507 def test17(self):1508 """single line #def with $ on methodName"""1509 self.verify("#def $testMeth:1234\n$testMeth",1510 "1234")1511 def test18(self):1512 """single line #def with an argument"""1513 self.verify("#def $testMeth($arg=1234):$arg\n$testMeth",1514 "1234")1515class DecoratorDirective(OutputTest):1516 def test1(self):1517 """single line #def with decorator"""1518 self.verify("#@ blah", "#@ blah")1519 self.verify("#@23 blah", "#@23 blah")1520 self.verify("#@@TR: comment", "#@@TR: comment")1521 self.verify("#from Cheetah.Tests.SyntaxAndOutput import testdecorator\n"1522 +"#@testdecorator"1523 +"\n#def $testMeth():1234\n$testMeth",1524 1525 "1234")1526 self.verify("#from Cheetah.Tests.SyntaxAndOutput import testdecorator\n"1527 +"#@testdecorator"1528 +"\n#block $testMeth():1234",1529 1530 "1234")1531 try:1532 self.verify(1533 "#from Cheetah.Tests.SyntaxAndOutput import testdecorator\n"1534 +"#@testdecorator\n sdf"1535 +"\n#def $testMeth():1234\n$testMeth", 1536 "1234")1537 except ParseError:1538 pass1539 else:1540 self.fail('should raise a ParseError')1541if versionTuple < (2,4):1542 del DecoratorDirective1543class BlockDirective(OutputTest):1544 def test1(self):1545 """#block without argstring"""1546 self.verify("#block testBlock\n1234\n#end block",1547 "1234\n")1548 self.verify("#block testBlock ##comment\n1234\n#end block",1549 "1234\n")1550 def test2(self):1551 """#block without argstring, gobble WS"""1552 self.verify(" #block testBlock \n1234\n #end block ",1553 "1234\n")1554 def test3(self):1555 """#block with argstring, gobble WS1556 Because blocks can be reused in multiple parts of the template arguments1557 (!!with defaults!!) can be given."""1558 1559 self.verify(" #block testBlock($a=999) \n1234-$a\n #end block ",1560 "1234-999\n")1561 def test4(self):1562 """#block with 2 args, gobble WS"""1563 self.verify(" #block testBlock($a=999, $b=444) \n1234-$a$b\n #end block ",1564 "1234-999444\n")1565 def test5(self):1566 """#block with 2 nested blocks1567 Blocks can be nested to any depth and the name of the block is optional1568 for the #end block part: #end block OR #end block [name] """1569 1570 self.verify("""#block testBlock1571this is a test block1572#block outerNest1573outer1574#block innerNest1575inner1576#end block innerNest1577#end block outerNest1578---1579#end block testBlock1580""",1581 "this is a test block\nouter\ninner\n---\n")1582 def test6(self):1583 """single line #block """1584 self.verify(1585 "#block testMeth: This is my block",1586 "This is my block")1587 def test7(self):1588 """single line #block with WS"""1589 self.verify(1590 "#block testMeth: This is my block",1591 "This is my block")1592 def test8(self):1593 """single line #block 1 escaped $placeholders"""1594 self.verify(1595 "#block testMeth: \$aFunc($anInt)",1596 "$aFunc(1)")1597 def test9(self):1598 """single line #block 1 escaped $placeholders + WS"""1599 self.verify(1600 "#block testMeth: \$aFunc( $anInt )",1601 "$aFunc( 1 )")1602 def test10(self):1603 """single line #block 1 escaped $placeholders + more WS"""1604 self.verify(1605 "#block testMeth : \$aFunc( $anInt )",1606 "$aFunc( 1 )")1607 def test11(self):1608 """multiline #block $ on argstring"""1609 self.verify("#block $testBlock\n1234\n#end block",1610 "1234\n")1611 def test12(self):1612 """single line #block with $ on methodName """1613 self.verify(1614 "#block $testMeth: This is my block",1615 "This is my block")1616 def test13(self):1617 """single line #block with an arg """1618 self.verify(1619 "#block $testMeth($arg='This is my block'): $arg",1620 "This is my block")1621 def test14(self):1622 """single line #block with None for content"""1623 self.verify(1624 """#block $testMeth: $None\ntest $testMeth-""",1625 "test -")1626 def test15(self):1627 """single line #block with nothing for content"""1628 self.verify(1629 """#block $testMeth: \nfoo\n#end block\ntest $testMeth-""",1630 "foo\ntest foo\n-")1631class IncludeDirective(OutputTest):1632 def setUp(self):1633 fp = open('parseTest.txt','w')1634 fp.write("$numOne $numTwo")1635 fp.flush()1636 fp.close1637 def tearDown(self):1638 if os.path.exists('parseTest.txt'):1639 os.remove('parseTest.txt')1640 def test1(self):1641 """#include raw of source $emptyString"""1642 self.verify("#include raw source=$emptyString",1643 "")1644 def test2(self):1645 """#include raw of source $blockToBeParsed"""1646 self.verify("#include raw source=$blockToBeParsed",1647 "$numOne $numTwo")1648 def test3(self):1649 """#include raw of 'parseTest.txt'"""1650 self.verify("#include raw 'parseTest.txt'",1651 "$numOne $numTwo")1652 def test4(self):1653 """#include raw of $includeFileName"""1654 self.verify("#include raw $includeFileName",1655 "$numOne $numTwo")1656 def test5(self):1657 """#include raw of $includeFileName, with WS"""1658 self.verify(" #include raw $includeFileName ",1659 "$numOne $numTwo")1660 def test6(self):1661 """#include raw of source= , with WS"""1662 self.verify(" #include raw source='This is my $Source '*2 ",1663 "This is my $Source This is my $Source ")1664 def test7(self):1665 """#include of $blockToBeParsed"""1666 self.verify("#include source=$blockToBeParsed",1667 "1 2")1668 1669 def test8(self):1670 """#include of $blockToBeParsed, with WS"""1671 self.verify(" #include source=$blockToBeParsed ",1672 "1 2")1673 def test9(self):1674 """#include of 'parseTest.txt', with WS"""1675 self.verify(" #include source=$blockToBeParsed ",1676 "1 2")1677 def test10(self):1678 """#include of "parseTest.txt", with WS"""1679 self.verify(" #include source=$blockToBeParsed ",1680 "1 2")1681 1682 def test11(self):1683 """#include of 'parseTest.txt', with WS and surrounding text"""1684 self.verify("aoeu\n #include source=$blockToBeParsed \naoeu",1685 "aoeu\n1 2aoeu")1686 def test12(self):1687 """#include of 'parseTest.txt', with WS and explicit closure"""1688 self.verify(" #include source=$blockToBeParsed# ",1689 " 1 2 ")1690class SilentDirective(OutputTest):1691 def test1(self):1692 """simple #silent"""1693 self.verify("#silent $aFunc",1694 "")1695 def test2(self):1696 """simple #silent"""1697 self.verify("#silent $anObj.callIt\n$anObj.callArg",1698 "1234")1699 self.verify("#silent $anObj.callIt ##comment\n$anObj.callArg",1700 "1234")1701 def test3(self):1702 """simple #silent"""1703 self.verify("#silent $anObj.callIt(99)\n$anObj.callArg",1704 "99")1705class SetDirective(OutputTest):1706 def test1(self):1707 """simple #set"""1708 self.verify("#set $testVar = 'blarg'\n$testVar",1709 "blarg")1710 self.verify("#set testVar = 'blarg'\n$testVar",1711 "blarg")1712 self.verify("#set testVar = 'blarg'##comment\n$testVar",1713 "blarg")1714 def test2(self):1715 """simple #set with no WS between operands"""1716 self.verify("#set $testVar='blarg'",1717 "")1718 def test3(self):1719 """#set + use of var"""1720 self.verify("#set $testVar = 'blarg'\n$testVar",1721 "blarg")1722 1723 def test4(self):1724 """#set + use in an #include"""1725 self.verify("#set global $aSetVar = 1234\n#include source=$includeBlock2",1726 "1 2 1234")1727 def test5(self):1728 """#set with a dictionary"""1729 self.verify( """#set $testDict = {'one':'one1','two':'two2','three':'three3'}1730$testDict.one1731$testDict.two""",1732 "one1\ntwo2")1733 def test6(self):1734 """#set with string, then used in #if block"""1735 1736 self.verify("""#set $test='a string'\n#if $test#blarg#end if""",1737 "blarg")1738 def test7(self):1739 """simple #set, gobble WS"""1740 self.verify(" #set $testVar = 'blarg' ",1741 "")1742 def test8(self):1743 """simple #set, don't gobble WS"""1744 self.verify(" #set $testVar = 'blarg'#---",1745 " ---")1746 def test9(self):1747 """simple #set with a list"""1748 self.verify(" #set $testVar = [1, 2, 3] \n$testVar",1749 "[1, 2, 3]")1750 def test10(self):1751 """simple #set global with a list"""1752 self.verify(" #set global $testVar = [1, 2, 3] \n$testVar",1753 "[1, 2, 3]")1754 def test11(self):1755 """simple #set global with a list and *cache1756 Caching only works with global #set vars. Local vars are not accesible1757 to the cache namespace.1758 """1759 1760 self.verify(" #set global $testVar = [1, 2, 3] \n$*testVar",1761 "[1, 2, 3]")1762 def test12(self):1763 """simple #set global with a list and *<int>*cache"""1764 self.verify(" #set global $testVar = [1, 2, 3] \n$*5*testVar",1765 "[1, 2, 3]")1766 def test13(self):1767 """simple #set with a list and *<float>*cache"""1768 self.verify(" #set global $testVar = [1, 2, 3] \n$*.5*testVar",1769 "[1, 2, 3]")1770 def test14(self):1771 """simple #set without NameMapper on"""1772 self.verify("""#compiler useNameMapper = 0\n#set $testVar = 1 \n$testVar""",1773 "1")1774 def test15(self):1775 """simple #set without $"""1776 self.verify("""#set testVar = 1 \n$testVar""",1777 "1")1778 def test16(self):1779 """simple #set global without $"""1780 self.verify("""#set global testVar = 1 \n$testVar""",1781 "1")1782 def test17(self):1783 """simple #set module without $"""1784 self.verify("""#set module __foo__ = 'bar'\n$__foo__""",1785 "bar")1786 def test18(self):1787 """#set with i,j=list style assignment"""1788 self.verify("""#set i,j = [1,2]\n$i$j""",1789 "12")1790 self.verify("""#set $i,$j = [1,2]\n$i$j""",1791 "12")1792 def test19(self):1793 """#set with (i,j)=list style assignment"""1794 self.verify("""#set (i,j) = [1,2]\n$i$j""",1795 "12")1796 self.verify("""#set ($i,$j) = [1,2]\n$i$j""",1797 "12")1798 def test20(self):1799 """#set with i, (j,k)=list style assignment"""1800 self.verify("""#set i, (j,k) = [1,(2,3)]\n$i$j$k""",1801 "123")1802 self.verify("""#set $i, ($j,$k) = [1,(2,3)]\n$i$j$k""",1803 "123")1804class IfDirective(OutputTest):1805 def test1(self):1806 """simple #if block"""1807 self.verify("#if 1\n$aStr\n#end if\n",1808 "blarg\n")1809 self.verify("#if 1:\n$aStr\n#end if\n",1810 "blarg\n")1811 self.verify("#if 1: \n$aStr\n#end if\n",1812 "blarg\n")1813 self.verify("#if 1: ##comment \n$aStr\n#end if\n",1814 "blarg\n")1815 self.verify("#if 1 ##comment \n$aStr\n#end if\n",1816 "blarg\n")1817 self.verify("#if 1##for i in range(10)#$i#end for##end if",1818 '0123456789')1819 self.verify("#if 1: #for i in range(10)#$i#end for",1820 '0123456789')1821 self.verify("#if 1: #for i in range(10):$i",1822 '0123456789')1823 def test2(self):1824 """simple #if block, with WS"""1825 self.verify(" #if 1\n$aStr\n #end if \n",1826 "blarg\n")1827 def test3(self):1828 """simple #if block, with WS and explicit closures"""1829 self.verify(" #if 1#\n$aStr\n #end if #--\n",1830 " \nblarg\n --\n")1831 def test4(self):1832 """#if block using $numOne"""1833 self.verify("#if $numOne\n$aStr\n#end if\n",1834 "blarg\n")1835 def test5(self):1836 """#if block using $zero"""1837 self.verify("#if $zero\n$aStr\n#end if\n",1838 "")1839 def test6(self):1840 """#if block using $emptyString"""1841 self.verify("#if $emptyString\n$aStr\n#end if\n",1842 "")1843 def test7(self):1844 """#if ... #else ... block using a $emptyString"""1845 self.verify("#if $emptyString\n$anInt\n#else\n$anInt - $anInt\n#end if",1846 "1 - 1\n")1847 1848 def test8(self):1849 """#if ... #elif ... #else ... block using a $emptyString"""1850 self.verify("#if $emptyString\n$c\n#elif $numOne\n$numOne\n#else\n$c - $c\n#end if",1851 "1\n")1852 def test9(self):1853 """#if 'not' test, with #slurp"""1854 self.verify("#if not $emptyString\n$aStr#slurp\n#end if\n",1855 "blarg")1856 def test10(self):1857 """#if block using $*emptyString1858 This should barf1859 """1860 try:1861 self.verify("#if $*emptyString\n$aStr\n#end if\n",1862 "")1863 except ParseError:1864 pass1865 else:1866 self.fail('This should barf')1867 def test11(self):1868 """#if block using invalid top-level $(placeholder) syntax - should barf"""1869 for badSyntax in ("#if $*5*emptyString\n$aStr\n#end if\n",1870 "#if ${emptyString}\n$aStr\n#end if\n",1871 "#if $(emptyString)\n$aStr\n#end if\n",1872 "#if $[emptyString]\n$aStr\n#end if\n",1873 "#if $!emptyString\n$aStr\n#end if\n",1874 ):1875 try:1876 self.verify(badSyntax, "")1877 except ParseError:1878 pass1879 else:1880 self.fail('This should barf')1881 1882 def test12(self):1883 """#if ... #else if ... #else ... block using a $emptyString1884 Same as test 8 but using else if instead of elif"""1885 self.verify("#if $emptyString\n$c\n#else if $numOne\n$numOne\n#else\n$c - $c\n#end if",1886 "1\n")1887 def test13(self):1888 """#if# ... #else # ... block using a $emptyString with """1889 self.verify("#if $emptyString# $anInt#else#$anInt - $anInt#end if",1890 "1 - 1")1891 def test14(self):1892 """single-line #if: simple"""1893 self.verify("#if $emptyString then 'true' else 'false'",1894 "false")1895 def test15(self):1896 """single-line #if: more complex"""1897 self.verify("#if $anInt then 'true' else 'false'",1898 "true")1899 def test16(self):1900 """single-line #if: with the words 'else' and 'then' in the output """1901 self.verify("#if ($anInt and not $emptyString==''' else ''') then $str('then') else 'else'",1902 "then")1903 def test17(self):1904 """single-line #if: """1905 self.verify("#if 1: foo\n#if 0: bar\n#if 1: foo",1906 "foo\nfoo")1907 self.verify("#if 1: foo\n#if 0: bar\n#if 1: foo",1908 "foo\nfoo")1909 def test18(self):1910 """single-line #if: \n#else: """1911 self.verify("#if 1: foo\n#elif 0: bar",1912 "foo\n")1913 self.verify("#if 1: foo\n#elif 0: bar\n#else: blarg\n",1914 "foo\n")1915 self.verify("#if 0: foo\n#elif 0: bar\n#else: blarg\n",1916 "blarg\n")1917class UnlessDirective(OutputTest):1918 1919 def test1(self):1920 """#unless 1"""1921 self.verify("#unless 1\n 1234 \n#end unless",1922 "")1923 self.verify("#unless 1:\n 1234 \n#end unless",1924 "")1925 self.verify("#unless 1: ##comment\n 1234 \n#end unless",1926 "")1927 self.verify("#unless 1 ##comment\n 1234 \n#end unless",1928 "")1929 def test2(self):1930 """#unless 0"""1931 self.verify("#unless 0\n 1234 \n#end unless",1932 " 1234 \n")1933 def test3(self):1934 """#unless $none"""1935 self.verify("#unless $none\n 1234 \n#end unless",1936 " 1234 \n")1937 def test4(self):1938 """#unless $numTwo"""1939 self.verify("#unless $numTwo\n 1234 \n#end unless",1940 "")1941 def test5(self):1942 """#unless $numTwo with WS"""1943 self.verify(" #unless $numTwo \n 1234 \n #end unless ",1944 "")1945 def test6(self):1946 """single-line #unless"""1947 self.verify("#unless 1: 1234", "")1948 self.verify("#unless 0: 1234", "1234")1949 self.verify("#unless 0: 1234\n"*2, "1234\n"*2)1950 1951class PSP(OutputTest):1952 1953 def test1(self):1954 """simple <%= [int] %>"""1955 self.verify("<%= 1234 %>", "1234")1956 def test2(self):1957 """simple <%= [string] %>"""1958 self.verify("<%= 'blarg' %>", "blarg")1959 def test3(self):1960 """simple <%= None %>"""1961 self.verify("<%= None %>", "")1962 def test4(self):1963 """simple <%= [string] %> + $anInt"""1964 self.verify("<%= 'blarg' %>$anInt", "blarg1")1965 def test5(self):1966 """simple <%= [EXPR] %> + $anInt"""1967 self.verify("<%= ('blarg'*2).upper() %>$anInt", "BLARGBLARG1")1968 def test6(self):1969 """for loop in <%%>"""1970 self.verify("<% for i in range(5):%>1<%end%>", "11111")1971 def test7(self):1972 """for loop in <%%> and using <%=i%>"""1973 self.verify("<% for i in range(5):%><%=i%><%end%>", "01234")1974 def test8(self):1975 """for loop in <% $%> and using <%=i%>"""1976 self.verify("""<% for i in range(5):1977 i=i*2$%><%=i%><%end%>""", "02468")1978 def test9(self):1979 """for loop in <% $%> and using <%=i%> plus extra text"""1980 self.verify("""<% for i in range(5):1981 i=i*2$%><%=i%>-<%end%>""", "0-2-4-6-8-")1982class WhileDirective(OutputTest):1983 def test1(self):1984 """simple #while with a counter"""1985 self.verify("#set $i = 0\n#while $i < 5\n$i#slurp\n#set $i += 1\n#end while",1986 "01234")1987class ContinueDirective(OutputTest):1988 def test1(self):1989 """#continue with a #while"""1990 self.verify("""#set $i = 01991#while $i < 51992#if $i == 31993 #set $i += 1 1994 #continue1995#end if1996$i#slurp1997#set $i += 11998#end while""",1999 "0124")2000 def test2(self):2001 """#continue with a #for"""2002 self.verify("""#for $i in range(5)2003#if $i == 32004 #continue2005#end if2006$i#slurp2007#end for""",2008 "0124")2009class BreakDirective(OutputTest):2010 def test1(self):2011 """#break with a #while"""2012 self.verify("""#set $i = 02013#while $i < 52014#if $i == 32015 #break2016#end if2017$i#slurp2018#set $i += 12019#end while""",2020 "012")2021 def test2(self):2022 """#break with a #for"""2023 self.verify("""#for $i in range(5)2024#if $i == 32025 #break2026#end if2027$i#slurp2028#end for""",2029 "012")2030class TryDirective(OutputTest):2031 def test1(self):2032 """simple #try 2033 """2034 self.verify("#try\n1234\n#except\nblarg\n#end try",2035 "1234\n")2036 def test2(self):2037 """#try / #except with #raise2038 """2039 self.verify("#try\n#raise ValueError\n#except\nblarg\n#end try",2040 "blarg\n")2041 2042 def test3(self):2043 """#try / #except with #raise + WS2044 Should gobble2045 """2046 self.verify(" #try \n #raise ValueError \n #except \nblarg\n #end try",2047 "blarg\n")2048 def test4(self):2049 """#try / #except with #raise + WS and leading text2050 2051 Shouldn't gobble2052 """2053 self.verify("--#try \n #raise ValueError \n #except \nblarg\n #end try#--",2054 "--\nblarg\n --")2055 def test5(self):2056 """nested #try / #except with #raise2057 """2058 self.verify(2059"""#try2060 #raise ValueError2061#except2062 #try2063 #raise ValueError2064 #except2065blarg2066 #end try2067#end try""",2068 "blarg\n")2069class PassDirective(OutputTest):2070 def test1(self):2071 """#pass in a #try / #except block2072 """2073 self.verify("#try\n#raise ValueError\n#except\n#pass\n#end try",2074 "")2075 def test2(self):2076 """#pass in a #try / #except block + WS2077 """2078 self.verify(" #try \n #raise ValueError \n #except \n #pass \n #end try",2079 "")2080class AssertDirective(OutputTest):2081 def test1(self):2082 """simple #assert 2083 """2084 self.verify("#set $x = 1234\n#assert $x == 1234",2085 "")2086 def test2(self):2087 """simple #assert that fails2088 """2089 def test(self=self):2090 self.verify("#set $x = 1234\n#assert $x == 999",2091 ""),2092 self.failUnlessRaises(AssertionError, test)2093 2094 def test3(self):2095 """simple #assert with WS2096 """2097 self.verify("#set $x = 1234\n #assert $x == 1234 ",2098 "")2099class RaiseDirective(OutputTest):2100 def test1(self):2101 """simple #raise ValueError2102 Should raise ValueError2103 """2104 def test(self=self):2105 self.verify("#raise ValueError",2106 ""),2107 self.failUnlessRaises(ValueError, test)2108 2109 def test2(self):2110 """#raise ValueError in #if block2111 Should raise ValueError2112 """2113 def test(self=self):2114 self.verify("#if 1\n#raise ValueError\n#end if\n",2115 "")2116 self.failUnlessRaises(ValueError, test)2117 def test3(self):2118 """#raise ValueError in #if block2119 Shouldn't raise ValueError2120 """2121 self.verify("#if 0\n#raise ValueError\n#else\nblarg#end if\n",2122 "blarg\n")2123class ImportDirective(OutputTest):2124 def test1(self):2125 """#import math2126 """2127 self.verify("#import math",2128 "")2129 def test2(self):2130 """#import math + WS2131 Should gobble2132 """2133 self.verify(" #import math ",2134 "")2135 def test3(self):2136 """#import math + WS + leading text2137 2138 Shouldn't gobble2139 """2140 self.verify(" -- #import math ",2141 " -- ")2142 2143 def test4(self):2144 """#from math import syn2145 """2146 self.verify("#from math import cos",2147 "")2148 def test5(self):2149 """#from math import cos + WS2150 Should gobble2151 """2152 self.verify(" #from math import cos ",2153 "")2154 def test6(self):2155 """#from math import cos + WS + leading text2156 Shouldn't gobble2157 """2158 self.verify(" -- #from math import cos ",2159 " -- ")2160 def test7(self):2161 """#from math import cos -- use it2162 """2163 self.verify("#from math import cos\n$cos(0)",2164 "1.0")2165 def test8(self):2166 """#from math import cos,tan,sin -- and use them2167 """2168 self.verify("#from math import cos, tan, sin\n$cos(0)-$tan(0)-$sin(0)",2169 "1.0-0.0-0.0")2170 def test9(self):2171 """#import os.path -- use it2172 """2173 2174 self.verify("#import os.path\n$os.path.exists('.')",2175 repr(True))2176 def test10(self):2177 """#import os.path -- use it with NameMapper turned off2178 """2179 self.verify("""##2180#compiler-settings2181useNameMapper=False2182#end compiler-settings2183#import os.path2184$os.path.exists('.')""",2185 repr(True))2186 def test11(self):2187 """#from math import *2188 """2189 2190 self.verify("#from math import *\n$pow(1,2) $log10(10)",2191 "1.0 1.0")2192class CompilerDirective(OutputTest):2193 def test1(self):2194 """overriding the commentStartToken2195 """2196 self.verify("""$anInt##comment2197#compiler commentStartToken = '//'2198$anInt//comment2199""",2200 "1\n1\n")2201 def test2(self):2202 """overriding and resetting the commentStartToken2203 """2204 self.verify("""$anInt##comment2205#compiler commentStartToken = '//'2206$anInt//comment2207#compiler reset2208$anInt//comment2209""",2210 "1\n1\n1//comment\n")2211class CompilerSettingsDirective(OutputTest):2212 2213 def test1(self):2214 """overriding the cheetahVarStartToken2215 """2216 self.verify("""$anInt2217#compiler-settings2218cheetahVarStartToken = @2219#end compiler-settings2220@anInt2221#compiler-settings reset2222$anInt2223""",2224 "1\n1\n1\n")2225 def test2(self):2226 """overriding the directiveStartToken2227 """2228 self.verify("""#set $x = 12342229$x2230#compiler-settings2231directiveStartToken = @2232#end compiler-settings2233@set $x = 12342234$x2235""",2236 "1234\n1234\n")2237 def test3(self):2238 """overriding the commentStartToken2239 """2240 self.verify("""$anInt##comment2241#compiler-settings2242commentStartToken = //2243#end compiler-settings2244$anInt//comment2245""",2246 "1\n1\n")2247if sys.platform.startswith('java'):2248 del CompilerDirective2249 del CompilerSettingsDirective2250class ExtendsDirective(OutputTest):2251 def test1(self):2252 """#extends Cheetah.Templates._SkeletonPage"""2253 self.verify("""#from Cheetah.Templates._SkeletonPage import _SkeletonPage2254#extends _SkeletonPage2255#implements respond2256$spacer()2257""",2258 '<img src="spacer.gif" width="1" height="1" alt="" />\n')2259 self.verify("""#from Cheetah.Templates._SkeletonPage import _SkeletonPage2260#extends _SkeletonPage2261#implements respond(foo=1234)2262$spacer()$foo2263""",2264 '<img src="spacer.gif" width="1" height="1" alt="" />1234\n')2265 def test2(self):2266 """#extends Cheetah.Templates.SkeletonPage without #import"""2267 self.verify("""#extends Cheetah.Templates.SkeletonPage2268#implements respond2269$spacer()2270""",2271 '<img src="spacer.gif" width="1" height="1" alt="" />\n')2272 def test3(self):2273 """#extends Cheetah.Templates.SkeletonPage.SkeletonPage without #import"""2274 self.verify("""#extends Cheetah.Templates.SkeletonPage.SkeletonPage2275#implements respond2276$spacer()2277""",2278 '<img src="spacer.gif" width="1" height="1" alt="" />\n')2279 def test4(self):2280 """#extends with globals and searchList test"""2281 self.verify("""#extends Cheetah.Templates.SkeletonPage2282#set global g="Hello"2283#implements respond2284$g $numOne2285""",2286 'Hello 1\n')2287class SuperDirective(OutputTest):2288 def test1(self):2289 tmpl1 = Template.compile('''$foo $bar(99)2290 #def foo: this is base foo2291 #def bar(arg): super-$arg''')2292 tmpl2 = tmpl1.subclass('''2293 #implements dummy2294 #def foo2295 #super2296 This is child foo2297 #super(trans=trans)2298 $bar(1234)2299 #end def2300 #def bar(arg): #super($arg)2301 ''')2302 expected = ('this is base foo '2303 'This is child foo\nthis is base foo '2304 'super-1234\n super-99')2305 assert str(tmpl2()).strip()==expected2306class ImportantExampleCases(OutputTest):2307 def test1(self):2308 """how to make a comma-delimited list"""2309 self.verify("""#set $sep = ''2310#for $letter in $letterList2311$sep$letter#slurp2312#set $sep = ', '2313#end for2314""",2315 "a, b, c")2316class FilterDirective(OutputTest):2317 convertEOLs=False2318 def _getCompilerSettings(self):2319 return {'useFilterArgsInPlaceholders':True}2320 2321 def test1(self):2322 """#filter Filter2323 """2324 self.verify("#filter Filter\n$none#end filter",2325 "")2326 self.verify("#filter Filter: $none",2327 "")2328 def test2(self):2329 """#filter ReplaceNone with WS2330 """2331 self.verify("#filter Filter \n$none#end filter",2332 "")2333 def test3(self):2334 """#filter MaxLen -- maxlen of 5"""2335 self.verify("#filter MaxLen \n${tenDigits, $maxlen=5}#end filter",2336 "12345")2337 def test4(self):2338 """#filter MaxLen -- no maxlen2339 """2340 self.verify("#filter MaxLen \n${tenDigits}#end filter",2341 "1234567890")2342 def test5(self):2343 """#filter WebSafe -- basic usage2344 """2345 self.verify("#filter WebSafe \n$webSafeTest#end filter",2346 "abc &lt;=&gt; &amp;")2347 def test6(self):2348 """#filter WebSafe -- also space2349 """2350 self.verify("#filter WebSafe \n${webSafeTest, $also=' '}#end filter",2351 "abc&nbsp;&lt;=&gt;&nbsp;&amp;")2352 2353 def test7(self):2354 """#filter WebSafe -- also space, without $ on the args2355 """2356 self.verify("#filter WebSafe \n${webSafeTest, also=' '}#end filter",2357 "abc&nbsp;&lt;=&gt;&nbsp;&amp;")2358 def test8(self):2359 """#filter Strip -- trailing newline2360 """2361 self.verify("#filter Strip\n$strip1#end filter",2362 "strippable whitespace\n")2363 def test9(self):2364 """#filter Strip -- no trailing newine2365 """2366 self.verify("#filter Strip\n$strip2#end filter",2367 "strippable whitespace")2368 def test10(self):2369 """#filter Strip -- multi-line2370 """2371 self.verify("#filter Strip\n$strip3#end filter",2372 "strippable whitespace\n1 2 3\n")2373 def test11(self):2374 """#filter StripSqueeze -- canonicalize all whitespace to ' '2375 """2376 self.verify("#filter StripSqueeze\n$strip3#end filter",2377 "strippable whitespace 1 2 3")2378class EchoDirective(OutputTest):2379 def test1(self):2380 """#echo 12342381 """2382 self.verify("#echo 1234",2383 "1234")2384class SilentDirective(OutputTest):2385 def test1(self):2386 """#silent 12342387 """2388 self.verify("#silent 1234",2389 "")2390class ErrorCatcherDirective(OutputTest):2391 pass2392class VarExists(OutputTest): # Template.varExists()2393 2394 def test1(self):2395 """$varExists('$anInt')2396 """2397 self.verify("$varExists('$anInt')",2398 repr(True))2399 def test2(self):2400 """$varExists('anInt')2401 """2402 self.verify("$varExists('anInt')",2403 repr(True))2404 def test3(self):2405 """$varExists('$anInt')2406 """2407 self.verify("$varExists('$bogus')",2408 repr(False))2409 def test4(self):2410 """$varExists('$anInt') combined with #if false2411 """2412 self.verify("#if $varExists('$bogus')\n1234\n#else\n999\n#end if",2413 "999\n")2414 def test5(self):2415 """$varExists('$anInt') combined with #if true2416 """2417 self.verify("#if $varExists('$anInt')\n1234\n#else\n999#end if",2418 "1234\n")2419class GetVar(OutputTest): # Template.getVar()2420 def test1(self):2421 """$getVar('$anInt')2422 """2423 self.verify("$getVar('$anInt')",2424 "1")2425 def test2(self):2426 """$getVar('anInt')2427 """2428 self.verify("$getVar('anInt')",2429 "1")2430 def test3(self):2431 """$self.getVar('anInt')2432 """2433 self.verify("$self.getVar('anInt')",2434 "1")2435 2436 def test4(self):2437 """$getVar('bogus', 1234)2438 """2439 self.verify("$getVar('bogus', 1234)",2440 "1234")2441 2442 def test5(self):2443 """$getVar('$bogus', 1234)2444 """2445 self.verify("$getVar('$bogus', 1234)",2446 "1234")2447class MiscComplexSyntax(OutputTest):2448 def test1(self):2449 """Complex use of {},[] and () in a #set expression2450 ----2451 #set $c = {'A':0}[{}.get('a', {'a' : 'A'}['a'])]2452 $c2453 """2454 self.verify("#set $c = {'A':0}[{}.get('a', {'a' : 'A'}['a'])]\n$c",2455 "0")2456class CGI(OutputTest):2457 """CGI scripts with(out) the CGI environment and with(out) GET variables.2458 """2459 convertEOLs=False2460 2461 def _beginCGI(self): 2462 os.environ['REQUEST_METHOD'] = "GET"2463 def _endCGI(self): 2464 try:2465 del os.environ['REQUEST_METHOD']2466 except KeyError:2467 pass2468 _guaranteeNoCGI = _endCGI2469 def test1(self):2470 """A regular template."""2471 self._guaranteeNoCGI()2472 source = "#extends Cheetah.Tools.CGITemplate\n" + \2473 "#implements respond\n" + \2474 "$cgiHeaders#slurp\n" + \2475 "Hello, world!" 2476 self.verify(source, "Hello, world!")2477 def test2(self):2478 """A CGI script."""2479 self._beginCGI()2480 source = "#extends Cheetah.Tools.CGITemplate\n" + \2481 "#implements respond\n" + \2482 "$cgiHeaders#slurp\n" + \2483 "Hello, world!" 2484 self.verify(source, "Content-type: text/html\n\nHello, world!")2485 self._endCGI()2486 def test3(self):2487 """A (pseudo) Webware servlet.2488 2489 This uses the Python syntax escape to set2490 self._CHEETAH__isControlledByWebKit. 2491 We could instead do '#silent self._CHEETAH__isControlledByWebKit = True',2492 taking advantage of the fact that it will compile unchanged as long2493 as there's no '$' in the statement. (It won't compile with an '$'2494 because that would convert to a function call, and you can't assign2495 to a function call.) Because this isn't really being called from2496 Webware, we'd better not use any Webware services! Likewise, we'd2497 better not call $cgiImport() because it would be misled.2498 """2499 self._beginCGI()2500 source = "#extends Cheetah.Tools.CGITemplate\n" + \2501 "#implements respond\n" + \2502 "<% self._CHEETAH__isControlledByWebKit = True %>#slurp\n" + \2503 "$cgiHeaders#slurp\n" + \2504 "Hello, world!"2505 self.verify(source, "Hello, world!")2506 self._endCGI()2507 def test4(self):2508 """A CGI script with a GET variable."""2509 self._beginCGI()2510 os.environ['QUERY_STRING'] = "cgiWhat=world"2511 source = "#extends Cheetah.Tools.CGITemplate\n" + \2512 "#implements respond\n" + \2513 "$cgiHeaders#slurp\n" + \2514 "#silent $webInput(['cgiWhat'])##slurp\n" + \2515 "Hello, $cgiWhat!"2516 self.verify(source, 2517 "Content-type: text/html\n\nHello, world!")2518 del os.environ['QUERY_STRING']2519 self._endCGI()2520class WhitespaceAfterDirectiveTokens(OutputTest):2521 def _getCompilerSettings(self):2522 return {'allowWhitespaceAfterDirectiveStartToken':True}2523 def test1(self):2524 self.verify("# for i in range(10): $i",2525 "0123456789")2526 self.verify("# for i in range(10)\n$i# end for",2527 "0123456789")2528 self.verify("# for i in range(10)#$i#end for",2529 "0123456789")2530class DefmacroDirective(OutputTest):2531 def _getCompilerSettings(self):2532 def aMacro(src):2533 return '$aStr'2534 2535 return {'macroDirectives':{'aMacro':aMacro2536 }}2537 def test1(self):2538 self.verify("""\2539#defmacro inc: #set @src +=12540#set i = 12541#inc: $i2542$i""",2543 "2")2544 self.verify("""\2545#defmacro test2546#for i in range(10): @src2547#end defmacro2548#test: $i-foo#slurp2549#for i in range(3): $i""",2550 "0-foo1-foo2-foo3-foo4-foo5-foo6-foo7-foo8-foo9-foo012")2551 self.verify("""\2552#defmacro test2553#for i in range(10): @src2554#end defmacro2555#test: $i-foo2556#for i in range(3): $i""",2557 "0-foo\n1-foo\n2-foo\n3-foo\n4-foo\n5-foo\n6-foo\n7-foo\n8-foo\n9-foo\n012")2558 self.verify("""\2559#defmacro test: #for i in range(10): @src2560#test: $i-foo#slurp2561-#for i in range(3): $i""",2562 "0-foo1-foo2-foo3-foo4-foo5-foo6-foo7-foo8-foo9-foo-012")2563 self.verify("""\2564#defmacro test##for i in range(10): @src#end defmacro##slurp2565#test: $i-foo#slurp2566-#for i in range(3): $i""",2567 "0-foo1-foo2-foo3-foo4-foo5-foo6-foo7-foo8-foo9-foo-012")2568 self.verify("""\2569#defmacro testFoo: nothing2570#defmacro test(foo=1234): #for i in range(10): @src2571#test foo=234: $i-foo#slurp2572-#for i in range(3): $i""",2573 "0-foo1-foo2-foo3-foo4-foo5-foo6-foo7-foo8-foo9-foo-012")2574 self.verify("""\2575#defmacro testFoo: nothing2576#defmacro test(foo=1234): #for i in range(10): @src@foo2577#test foo='-foo'#$i#end test#-#for i in range(3): $i""",2578 "0-foo1-foo2-foo3-foo4-foo5-foo6-foo7-foo8-foo9-foo-012")2579 self.verify("""\2580#defmacro testFoo: nothing2581#defmacro test(foo=1234): #for i in range(10): @src.strip()@foo2582#test foo='-foo': $i2583-#for i in range(3): $i""",2584 "0-foo1-foo2-foo3-foo4-foo5-foo6-foo7-foo8-foo9-foo-012")2585 def test2(self):2586 self.verify("#aMacro: foo",2587 "blarg")2588 self.verify("#defmacro nested: @macros.aMacro(@src)\n#nested: foo",2589 "blarg")2590class Indenter(OutputTest):2591 convertEOLs=False2592 2593 source = """2594public class X2595{2596 #for $method in $methods2597 $getMethod($method)2598 2599 #end for2600}2601//end of class2602#def getMethod($method)2603 #indent ++2604 public $getType($method) ${method.Name}($getParams($method.Params));2605 #indent --2606#end def2607#def getParams($params)2608 #indent off2609 #for $counter in $range($len($params))2610 #if $counter == len($params) - 12611 $params[$counter]#slurp2612 #else:2613 $params[$counter], 2614 #end if2615 #end for2616 #indent on2617#end def2618#def getType($method)2619 #indent push2620 #indent=02621 #if $method.Type == "VT_VOID"2622 void#slurp2623 #elif $method.Type == "VT_INT"2624 int#slurp2625 #elif $method.Type == "VT_VARIANT"2626 Object#slurp2627 #end if2628 #indent pop2629#end def2630"""2631 control = """2632public class X2633{2634 public void Foo(2635 _input, 2636 _output);2637 public int Bar(2638 _str1, 2639 str2, 2640 _str3);2641 public Object Add(2642 value1, 2643 value);2644}2645//end of class2646"""2647 def _getCompilerSettings(self):2648 return {'useFilterArgsInPlaceholders':True}2649 def searchList(self): # Inside Indenter class.2650 class Method:2651 def __init__(self, _name, _type, *_params):2652 self.Name = _name2653 self.Type = _type2654 self.Params = _params2655 methods = [Method("Foo", "VT_VOID", "_input", "_output"),2656 Method("Bar", "VT_INT", "_str1", "str2", "_str3"),2657 Method("Add", "VT_VARIANT", "value1", "value")]2658 return [{"methods": methods}]2659 def test1(self): # Inside Indenter class.2660 self.verify(self.source, self.control)2661##################################################2662## CREATE CONVERTED EOL VERSIONS OF THE TEST CASES2663if OutputTest._useNewStyleCompilation and versionTuple >= (2,3):2664 extraCompileKwArgsForDiffBaseclass = {'baseclass':dict}2665else:2666 extraCompileKwArgsForDiffBaseclass = {'baseclass':object}2667 2668for klass in [var for var in globals().values()2669 if type(var) == types.ClassType and issubclass(var, unittest.TestCase)]:2670 name = klass.__name__ 2671 if hasattr(klass,'convertEOLs') and klass.convertEOLs:2672 win32Src = r"class %(name)s_Win32EOL(%(name)s): _EOLreplacement = '\r\n'"%locals()2673 macSrc = r"class %(name)s_MacEOL(%(name)s): _EOLreplacement = '\r'"%locals()2674 #print win32Src...

Full Screen

Full Screen

li_boost_shared_ptr_runme.py

Source:li_boost_shared_ptr_runme.py Github

copy

Full Screen

1import li_boost_shared_ptr2import gc3debug = False4# simple shared_ptr usage - created in C++5class li_boost_shared_ptr_runme:6 def main(self):7 if (debug):8 print "Started"9 li_boost_shared_ptr.cvar.debug_shared = debug10 # Change loop count to run for a long time to monitor memory11 loopCount = 1 # 500012 for i in range(0, loopCount):13 self.runtest()14 # Expect 1 instance - the one global variable (GlobalValue)15 if (li_boost_shared_ptr.Klass_getTotal_count() != 1):16 raise RuntimeError("Klass.total_count=%s" %17 li_boost_shared_ptr.Klass.getTotal_count())18 wrapper_count = li_boost_shared_ptr.shared_ptr_wrapper_count()19 if (wrapper_count != li_boost_shared_ptr.NOT_COUNTING):20 # Expect 1 instance - the one global variable (GlobalSmartValue)21 if (wrapper_count != 1):22 raise RuntimeError(23 "shared_ptr wrapper count=%s" % wrapper_count)24 if (debug):25 print "Finished"26 def runtest(self):27 # simple shared_ptr usage - created in C++28 k = li_boost_shared_ptr.Klass("me oh my")29 val = k.getValue()30 self.verifyValue("me oh my", val)31 self.verifyCount(1, k)32 # simple shared_ptr usage - not created in C++33 k = li_boost_shared_ptr.factorycreate()34 val = k.getValue()35 self.verifyValue("factorycreate", val)36 self.verifyCount(1, k)37 # pass by shared_ptr38 k = li_boost_shared_ptr.Klass("me oh my")39 kret = li_boost_shared_ptr.smartpointertest(k)40 val = kret.getValue()41 self.verifyValue("me oh my smartpointertest", val)42 self.verifyCount(2, k)43 self.verifyCount(2, kret)44 # pass by shared_ptr pointer45 k = li_boost_shared_ptr.Klass("me oh my")46 kret = li_boost_shared_ptr.smartpointerpointertest(k)47 val = kret.getValue()48 self.verifyValue("me oh my smartpointerpointertest", val)49 self.verifyCount(2, k)50 self.verifyCount(2, kret)51 # pass by shared_ptr reference52 k = li_boost_shared_ptr.Klass("me oh my")53 kret = li_boost_shared_ptr.smartpointerreftest(k)54 val = kret.getValue()55 self.verifyValue("me oh my smartpointerreftest", val)56 self.verifyCount(2, k)57 self.verifyCount(2, kret)58 # pass by shared_ptr pointer reference59 k = li_boost_shared_ptr.Klass("me oh my")60 kret = li_boost_shared_ptr.smartpointerpointerreftest(k)61 val = kret.getValue()62 self.verifyValue("me oh my smartpointerpointerreftest", val)63 self.verifyCount(2, k)64 self.verifyCount(2, kret)65 # const pass by shared_ptr66 k = li_boost_shared_ptr.Klass("me oh my")67 kret = li_boost_shared_ptr.constsmartpointertest(k)68 val = kret.getValue()69 self.verifyValue("me oh my", val)70 self.verifyCount(2, k)71 self.verifyCount(2, kret)72 # const pass by shared_ptr pointer73 k = li_boost_shared_ptr.Klass("me oh my")74 kret = li_boost_shared_ptr.constsmartpointerpointertest(k)75 val = kret.getValue()76 self.verifyValue("me oh my", val)77 self.verifyCount(2, k)78 self.verifyCount(2, kret)79 # const pass by shared_ptr reference80 k = li_boost_shared_ptr.Klass("me oh my")81 kret = li_boost_shared_ptr.constsmartpointerreftest(k)82 val = kret.getValue()83 self.verifyValue("me oh my", val)84 self.verifyCount(2, k)85 self.verifyCount(2, kret)86 # pass by value87 k = li_boost_shared_ptr.Klass("me oh my")88 kret = li_boost_shared_ptr.valuetest(k)89 val = kret.getValue()90 self.verifyValue("me oh my valuetest", val)91 self.verifyCount(1, k)92 self.verifyCount(1, kret)93 # pass by pointer94 k = li_boost_shared_ptr.Klass("me oh my")95 kret = li_boost_shared_ptr.pointertest(k)96 val = kret.getValue()97 self.verifyValue("me oh my pointertest", val)98 self.verifyCount(1, k)99 self.verifyCount(1, kret)100 # pass by reference101 k = li_boost_shared_ptr.Klass("me oh my")102 kret = li_boost_shared_ptr.reftest(k)103 val = kret.getValue()104 self.verifyValue("me oh my reftest", val)105 self.verifyCount(1, k)106 self.verifyCount(1, kret)107 # pass by pointer reference108 k = li_boost_shared_ptr.Klass("me oh my")109 kret = li_boost_shared_ptr.pointerreftest(k)110 val = kret.getValue()111 self.verifyValue("me oh my pointerreftest", val)112 self.verifyCount(1, k)113 self.verifyCount(1, kret)114 # null tests115 k = None116 if (li_boost_shared_ptr.smartpointertest(k) != None):117 raise RuntimeError("return was not null")118 if (li_boost_shared_ptr.smartpointerpointertest(k) != None):119 raise RuntimeError("return was not null")120 if (li_boost_shared_ptr.smartpointerreftest(k) != None):121 raise RuntimeError("return was not null")122 if (li_boost_shared_ptr.smartpointerpointerreftest(k) != None):123 raise RuntimeError("return was not null")124 if (li_boost_shared_ptr.nullsmartpointerpointertest(None) != "null pointer"):125 raise RuntimeError("not null smartpointer pointer")126 try:127 li_boost_shared_ptr.valuetest(k)128 raise RuntimeError("Failed to catch null pointer")129 except ValueError:130 pass131 if (li_boost_shared_ptr.pointertest(k) != None):132 raise RuntimeError("return was not null")133 try:134 li_boost_shared_ptr.reftest(k)135 raise RuntimeError("Failed to catch null pointer")136 except ValueError:137 pass138 # $owner139 k = li_boost_shared_ptr.pointerownertest()140 val = k.getValue()141 self.verifyValue("pointerownertest", val)142 self.verifyCount(1, k)143 k = li_boost_shared_ptr.smartpointerpointerownertest()144 val = k.getValue()145 self.verifyValue("smartpointerpointerownertest", val)146 self.verifyCount(1, k)147 # //////////////////////////////// Derived class //////////////////////148 # derived pass by shared_ptr149 k = li_boost_shared_ptr.KlassDerived("me oh my")150 kret = li_boost_shared_ptr.derivedsmartptrtest(k)151 val = kret.getValue()152 self.verifyValue("me oh my derivedsmartptrtest-Derived", val)153 self.verifyCount(2, k)154 self.verifyCount(2, kret)155 # derived pass by shared_ptr pointer156 k = li_boost_shared_ptr.KlassDerived("me oh my")157 kret = li_boost_shared_ptr.derivedsmartptrpointertest(k)158 val = kret.getValue()159 self.verifyValue("me oh my derivedsmartptrpointertest-Derived", val)160 self.verifyCount(2, k)161 self.verifyCount(2, kret)162 # derived pass by shared_ptr ref163 k = li_boost_shared_ptr.KlassDerived("me oh my")164 kret = li_boost_shared_ptr.derivedsmartptrreftest(k)165 val = kret.getValue()166 self.verifyValue("me oh my derivedsmartptrreftest-Derived", val)167 self.verifyCount(2, k)168 self.verifyCount(2, kret)169 # derived pass by shared_ptr pointer ref170 k = li_boost_shared_ptr.KlassDerived("me oh my")171 kret = li_boost_shared_ptr.derivedsmartptrpointerreftest(k)172 val = kret.getValue()173 self.verifyValue("me oh my derivedsmartptrpointerreftest-Derived", val)174 self.verifyCount(2, k)175 self.verifyCount(2, kret)176 # derived pass by pointer177 k = li_boost_shared_ptr.KlassDerived("me oh my")178 kret = li_boost_shared_ptr.derivedpointertest(k)179 val = kret.getValue()180 self.verifyValue("me oh my derivedpointertest-Derived", val)181 self.verifyCount(1, k)182 self.verifyCount(1, kret)183 # derived pass by ref184 k = li_boost_shared_ptr.KlassDerived("me oh my")185 kret = li_boost_shared_ptr.derivedreftest(k)186 val = kret.getValue()187 self.verifyValue("me oh my derivedreftest-Derived", val)188 self.verifyCount(1, k)189 self.verifyCount(1, kret)190 # //////////////////////////////// Derived and base class mixed ///////191 # pass by shared_ptr (mixed)192 k = li_boost_shared_ptr.KlassDerived("me oh my")193 kret = li_boost_shared_ptr.smartpointertest(k)194 val = kret.getValue()195 self.verifyValue("me oh my smartpointertest-Derived", val)196 self.verifyCount(2, k)197 self.verifyCount(2, kret)198 # pass by shared_ptr pointer (mixed)199 k = li_boost_shared_ptr.KlassDerived("me oh my")200 kret = li_boost_shared_ptr.smartpointerpointertest(k)201 val = kret.getValue()202 self.verifyValue("me oh my smartpointerpointertest-Derived", val)203 self.verifyCount(2, k)204 self.verifyCount(2, kret)205 # pass by shared_ptr reference (mixed)206 k = li_boost_shared_ptr.KlassDerived("me oh my")207 kret = li_boost_shared_ptr.smartpointerreftest(k)208 val = kret.getValue()209 self.verifyValue("me oh my smartpointerreftest-Derived", val)210 self.verifyCount(2, k)211 self.verifyCount(2, kret)212 # pass by shared_ptr pointer reference (mixed)213 k = li_boost_shared_ptr.KlassDerived("me oh my")214 kret = li_boost_shared_ptr.smartpointerpointerreftest(k)215 val = kret.getValue()216 self.verifyValue("me oh my smartpointerpointerreftest-Derived", val)217 self.verifyCount(2, k)218 self.verifyCount(2, kret)219 # pass by value (mixed)220 k = li_boost_shared_ptr.KlassDerived("me oh my")221 kret = li_boost_shared_ptr.valuetest(k)222 val = kret.getValue()223 self.verifyValue("me oh my valuetest", val) # note slicing224 self.verifyCount(1, k)225 self.verifyCount(1, kret)226 # pass by pointer (mixed)227 k = li_boost_shared_ptr.KlassDerived("me oh my")228 kret = li_boost_shared_ptr.pointertest(k)229 val = kret.getValue()230 self.verifyValue("me oh my pointertest-Derived", val)231 self.verifyCount(1, k)232 self.verifyCount(1, kret)233 # pass by ref (mixed)234 k = li_boost_shared_ptr.KlassDerived("me oh my")235 kret = li_boost_shared_ptr.reftest(k)236 val = kret.getValue()237 self.verifyValue("me oh my reftest-Derived", val)238 self.verifyCount(1, k)239 self.verifyCount(1, kret)240 # //////////////////////////////// Overloading tests //////////////////241 # Base class242 k = li_boost_shared_ptr.Klass("me oh my")243 self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval")244 self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref")245 self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr")246 self.verifyValue(247 li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref")248 self.verifyValue(249 li_boost_shared_ptr.overload_smartbyval(k), "smartbyval")250 self.verifyValue(251 li_boost_shared_ptr.overload_smartbyref(k), "smartbyref")252 self.verifyValue(253 li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr")254 self.verifyValue(255 li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref")256 # Derived class257 k = li_boost_shared_ptr.KlassDerived("me oh my")258 self.verifyValue(li_boost_shared_ptr.overload_rawbyval(k), "rawbyval")259 self.verifyValue(li_boost_shared_ptr.overload_rawbyref(k), "rawbyref")260 self.verifyValue(li_boost_shared_ptr.overload_rawbyptr(k), "rawbyptr")261 self.verifyValue(262 li_boost_shared_ptr.overload_rawbyptrref(k), "rawbyptrref")263 self.verifyValue(264 li_boost_shared_ptr.overload_smartbyval(k), "smartbyval")265 self.verifyValue(266 li_boost_shared_ptr.overload_smartbyref(k), "smartbyref")267 self.verifyValue(268 li_boost_shared_ptr.overload_smartbyptr(k), "smartbyptr")269 self.verifyValue(270 li_boost_shared_ptr.overload_smartbyptrref(k), "smartbyptrref")271 # 3rd derived class272 k = li_boost_shared_ptr.Klass3rdDerived("me oh my")273 val = k.getValue()274 self.verifyValue("me oh my-3rdDerived", val)275 self.verifyCount(1, k)276 val = li_boost_shared_ptr.test3rdupcast(k)277 self.verifyValue("me oh my-3rdDerived", val)278 self.verifyCount(1, k)279 # //////////////////////////////// Member variables ///////////////////280 # smart pointer by value281 m = li_boost_shared_ptr.MemberVariables()282 k = li_boost_shared_ptr.Klass("smart member value")283 m.SmartMemberValue = k284 val = k.getValue()285 self.verifyValue("smart member value", val)286 self.verifyCount(2, k)287 kmember = m.SmartMemberValue288 val = kmember.getValue()289 self.verifyValue("smart member value", val)290 self.verifyCount(3, kmember)291 self.verifyCount(3, k)292 del m293 self.verifyCount(2, kmember)294 self.verifyCount(2, k)295 # smart pointer by pointer296 m = li_boost_shared_ptr.MemberVariables()297 k = li_boost_shared_ptr.Klass("smart member pointer")298 m.SmartMemberPointer = k299 val = k.getValue()300 self.verifyValue("smart member pointer", val)301 self.verifyCount(1, k)302 kmember = m.SmartMemberPointer303 val = kmember.getValue()304 self.verifyValue("smart member pointer", val)305 self.verifyCount(2, kmember)306 self.verifyCount(2, k)307 del m308 self.verifyCount(2, kmember)309 self.verifyCount(2, k)310 # smart pointer by reference311 m = li_boost_shared_ptr.MemberVariables()312 k = li_boost_shared_ptr.Klass("smart member reference")313 m.SmartMemberReference = k314 val = k.getValue()315 self.verifyValue("smart member reference", val)316 self.verifyCount(2, k)317 kmember = m.SmartMemberReference318 val = kmember.getValue()319 self.verifyValue("smart member reference", val)320 self.verifyCount(3, kmember)321 self.verifyCount(3, k)322 # The C++ reference refers to SmartMemberValue...323 kmemberVal = m.SmartMemberValue324 val = kmember.getValue()325 self.verifyValue("smart member reference", val)326 self.verifyCount(4, kmemberVal)327 self.verifyCount(4, kmember)328 self.verifyCount(4, k)329 del m330 self.verifyCount(3, kmemberVal)331 self.verifyCount(3, kmember)332 self.verifyCount(3, k)333 # plain by value334 m = li_boost_shared_ptr.MemberVariables()335 k = li_boost_shared_ptr.Klass("plain member value")336 m.MemberValue = k337 val = k.getValue()338 self.verifyValue("plain member value", val)339 self.verifyCount(1, k)340 kmember = m.MemberValue341 val = kmember.getValue()342 self.verifyValue("plain member value", val)343 self.verifyCount(1, kmember)344 self.verifyCount(1, k)345 del m346 self.verifyCount(1, kmember)347 self.verifyCount(1, k)348 # plain by pointer349 m = li_boost_shared_ptr.MemberVariables()350 k = li_boost_shared_ptr.Klass("plain member pointer")351 m.MemberPointer = k352 val = k.getValue()353 self.verifyValue("plain member pointer", val)354 self.verifyCount(1, k)355 kmember = m.MemberPointer356 val = kmember.getValue()357 self.verifyValue("plain member pointer", val)358 self.verifyCount(1, kmember)359 self.verifyCount(1, k)360 del m361 self.verifyCount(1, kmember)362 self.verifyCount(1, k)363 # plain by reference364 m = li_boost_shared_ptr.MemberVariables()365 k = li_boost_shared_ptr.Klass("plain member reference")366 m.MemberReference = k367 val = k.getValue()368 self.verifyValue("plain member reference", val)369 self.verifyCount(1, k)370 kmember = m.MemberReference371 val = kmember.getValue()372 self.verifyValue("plain member reference", val)373 self.verifyCount(1, kmember)374 self.verifyCount(1, k)375 del m376 self.verifyCount(1, kmember)377 self.verifyCount(1, k)378 # null member variables379 m = li_boost_shared_ptr.MemberVariables()380 # shared_ptr by value381 k = m.SmartMemberValue382 if (k != None):383 raise RuntimeError("expected null")384 m.SmartMemberValue = None385 k = m.SmartMemberValue386 if (k != None):387 raise RuntimeError("expected null")388 self.verifyCount(0, k)389 # plain by value390 try:391 m.MemberValue = None392 raise RuntimeError("Failed to catch null pointer")393 except ValueError:394 pass395 # ////////////////////////////////// Global variables /////////////////396 # smart pointer397 kglobal = li_boost_shared_ptr.cvar.GlobalSmartValue398 if (kglobal != None):399 raise RuntimeError("expected null")400 k = li_boost_shared_ptr.Klass("smart global value")401 li_boost_shared_ptr.cvar.GlobalSmartValue = k402 self.verifyCount(2, k)403 kglobal = li_boost_shared_ptr.cvar.GlobalSmartValue404 val = kglobal.getValue()405 self.verifyValue("smart global value", val)406 self.verifyCount(3, kglobal)407 self.verifyCount(3, k)408 self.verifyValue(409 "smart global value", li_boost_shared_ptr.cvar.GlobalSmartValue.getValue())410 li_boost_shared_ptr.cvar.GlobalSmartValue = None411 # plain value412 k = li_boost_shared_ptr.Klass("global value")413 li_boost_shared_ptr.cvar.GlobalValue = k414 self.verifyCount(1, k)415 kglobal = li_boost_shared_ptr.cvar.GlobalValue416 val = kglobal.getValue()417 self.verifyValue("global value", val)418 self.verifyCount(1, kglobal)419 self.verifyCount(1, k)420 self.verifyValue(421 "global value", li_boost_shared_ptr.cvar.GlobalValue.getValue())422 try:423 li_boost_shared_ptr.cvar.GlobalValue = None424 raise RuntimeError("Failed to catch null pointer")425 except ValueError:426 pass427 # plain pointer428 kglobal = li_boost_shared_ptr.cvar.GlobalPointer429 if (kglobal != None):430 raise RuntimeError("expected null")431 k = li_boost_shared_ptr.Klass("global pointer")432 li_boost_shared_ptr.cvar.GlobalPointer = k433 self.verifyCount(1, k)434 kglobal = li_boost_shared_ptr.cvar.GlobalPointer435 val = kglobal.getValue()436 self.verifyValue("global pointer", val)437 self.verifyCount(1, kglobal)438 self.verifyCount(1, k)439 li_boost_shared_ptr.cvar.GlobalPointer = None440 # plain reference441 k = li_boost_shared_ptr.Klass("global reference")442 li_boost_shared_ptr.cvar.GlobalReference = k443 self.verifyCount(1, k)444 kglobal = li_boost_shared_ptr.cvar.GlobalReference445 val = kglobal.getValue()446 self.verifyValue("global reference", val)447 self.verifyCount(1, kglobal)448 self.verifyCount(1, k)449 try:450 li_boost_shared_ptr.cvar.GlobalReference = None451 raise RuntimeError("Failed to catch null pointer")452 except ValueError:453 pass454 # ////////////////////////////////// Templates ////////////////////////455 pid = li_boost_shared_ptr.PairIntDouble(10, 20.2)456 if (pid.baseVal1 != 20 or pid.baseVal2 != 40.4):457 raise RuntimeError("Base values wrong")458 if (pid.val1 != 10 or pid.val2 != 20.2):459 raise RuntimeError("Derived Values wrong")460 def verifyValue(self, expected, got):461 if (expected != got):462 raise RuntimeError(463 "verify value failed. Expected: ", expected, " Got: ", got)464 def verifyCount(self, expected, k):465 got = li_boost_shared_ptr.use_count(k)466 if (expected != got):467 raise RuntimeError(468 "verify use_count failed. Expected: ", expected, " Got: ", got)469runme = li_boost_shared_ptr_runme()...

Full Screen

Full Screen

testCli.js

Source:testCli.js Github

copy

Full Screen

1/* ***** BEGIN LICENSE BLOCK *****2 * Version: MPL 1.1/GPL 2.0/LGPL 2.13 *4 * The contents of this file are subject to the Mozilla Public License Version5 * 1.1 (the "License"); you may not use this file except in compliance with6 * the License. You may obtain a copy of the License at7 * http://www.mozilla.org/MPL/8 *9 * Software distributed under the License is distributed on an "AS IS" basis,10 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License11 * for the specific language governing rights and limitations under the12 * License.13 *14 * The Original Code is Skywriter.15 *16 * The Initial Developer of the Original Code is17 * Mozilla.18 * Portions created by the Initial Developer are Copyright (C) 200919 * the Initial Developer. All Rights Reserved.20 *21 * Contributor(s):22 * Joe Walker (jwalker@mozilla.com)23 *24 * Alternatively, the contents of this file may be used under the terms of25 * either the GNU General Public License Version 2 or later (the "GPL"), or26 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),27 * in which case the provisions of the GPL or the LGPL are applicable instead28 * of those above. If you wish to allow use of your version of this file only29 * under the terms of either the GPL or the LGPL, and not to allow others to30 * use your version of this file under the terms of the MPL, indicate your31 * decision by deleting the provisions above and replace them with the notice32 * and other provisions required by the GPL or the LGPL. If you do not delete33 * the provisions above, a recipient may use your version of this file under34 * the terms of any one of the MPL, the GPL or the LGPL.35 *36 * ***** END LICENSE BLOCK ***** */37define(function(require, exports, module) {38var test = require('cockpit/test/assert').test;39var Status = require('pilot/types').Status;40var settings = require('pilot/settings').settings;41var tokenize = require('cockpit/cli')._tokenize;42var split = require('cockpit/cli')._split;43var CliRequisition = require('cockpit/cli').CliRequisition;44var canon = require('pilot/canon');45var tsvCommandSpec = {46 name: 'tsv',47 params: [48 { name: 'setting', type: 'setting', defaultValue: null },49 { name: 'value', type: 'settingValue', defaultValue: null }50 ],51 exec: function(env, args, request) { }52};53var tsrCommandSpec = {54 name: 'tsr',55 params: [ { name: 'text', type: 'text' } ],56 exec: function(env, args, request) { }57};58exports.testAll = function() {59 canon.addCommand(tsvCommandSpec);60 canon.addCommand(tsrCommandSpec);61 exports.testTokenize();62 exports.testSplit();63 exports.testCli();64 canon.removeCommand(tsvCommandSpec);65 canon.removeCommand(tsrCommandSpec);66 return "testAll Completed";67};68exports.testTokenize = function() {69 var args;70 var cli = new CliRequisition();71 args = cli._tokenize('');72 test.verifyEqual(1, args.length);73 test.verifyEqual('', args[0].text);74 test.verifyEqual(0, args[0].start);75 test.verifyEqual(0, args[0].end);76 test.verifyEqual('', args[0].prefix);77 test.verifyEqual('', args[0].suffix);78 args = cli._tokenize('s');79 test.verifyEqual(1, args.length);80 test.verifyEqual('s', args[0].text);81 test.verifyEqual(0, args[0].start);82 test.verifyEqual(1, args[0].end);83 test.verifyEqual('', args[0].prefix);84 test.verifyEqual('', args[0].suffix);85 args = cli._tokenize(' ');86 test.verifyEqual(1, args.length);87 test.verifyEqual('', args[0].text);88 test.verifyEqual(1, args[0].start);89 test.verifyEqual(1, args[0].end);90 test.verifyEqual(' ', args[0].prefix);91 test.verifyEqual('', args[0].suffix);92 args = cli._tokenize('s s');93 test.verifyEqual(2, args.length);94 test.verifyEqual('s', args[0].text);95 test.verifyEqual(0, args[0].start);96 test.verifyEqual(1, args[0].end);97 test.verifyEqual('', args[0].prefix);98 test.verifyEqual('', args[0].suffix);99 test.verifyEqual('s', args[1].text);100 test.verifyEqual(2, args[1].start);101 test.verifyEqual(3, args[1].end);102 test.verifyEqual(' ', args[1].prefix);103 test.verifyEqual('', args[1].suffix);104 args = cli._tokenize(' 1234 \'12 34\'');105 test.verifyEqual(2, args.length);106 test.verifyEqual('1234', args[0].text);107 test.verifyEqual(1, args[0].start);108 test.verifyEqual(5, args[0].end);109 test.verifyEqual(' ', args[0].prefix);110 test.verifyEqual('', args[0].suffix);111 test.verifyEqual('12 34', args[1].text);112 test.verifyEqual(7, args[1].start);113 test.verifyEqual(14, args[1].end);114 test.verifyEqual(' \'', args[1].prefix);115 test.verifyEqual('\'', args[1].suffix);116 args = cli._tokenize('12\'34 "12 34" \\'); // 12'34 "12 34" \117 test.verifyEqual(3, args.length);118 test.verifyEqual('12\'34', args[0].text);119 test.verifyEqual(0, args[0].start);120 test.verifyEqual(5, args[0].end);121 test.verifyEqual('', args[0].prefix);122 test.verifyEqual('', args[0].suffix);123 test.verifyEqual('12 34', args[1].text);124 test.verifyEqual(6, args[1].start);125 test.verifyEqual(13, args[1].end);126 test.verifyEqual(' "', args[1].prefix);127 test.verifyEqual('"', args[1].suffix);128 test.verifyEqual('\\', args[2].text);129 test.verifyEqual(14, args[2].start);130 test.verifyEqual(15, args[2].end);131 test.verifyEqual(' ', args[2].prefix);132 test.verifyEqual('', args[2].suffix);133 args = cli._tokenize('a\\ b \\t\\n\\r \\\'x\\\" \'d'); // a_b \t\n\r \'x\" 'd134 test.verifyEqual(4, args.length);135 test.verifyEqual('a b', args[0].text);136 test.verifyEqual(0, args[0].start);137 test.verifyEqual(3, args[0].end);138 test.verifyEqual('', args[0].prefix);139 test.verifyEqual('', args[0].suffix);140 test.verifyEqual('\t\n\r', args[1].text);141 test.verifyEqual(4, args[1].start);142 test.verifyEqual(7, args[1].end);143 test.verifyEqual(' ', args[1].prefix);144 test.verifyEqual('', args[1].suffix);145 test.verifyEqual('\'x"', args[2].text);146 test.verifyEqual(8, args[2].start);147 test.verifyEqual(11, args[2].end);148 test.verifyEqual(' ', args[2].prefix);149 test.verifyEqual('', args[2].suffix);150 test.verifyEqual('d', args[3].text);151 test.verifyEqual(13, args[3].start);152 test.verifyEqual(14, args[3].end);153 test.verifyEqual(' \'', args[3].prefix);154 test.verifyEqual('', args[3].suffix);155 return "testTokenize Completed";156};157exports.testSplit = function() {158 var args;159 var cli = new CliRequisition();160 args = cli._tokenize('s');161 cli._split(args);162 test.verifyEqual(1, args.length);163 test.verifyEqual('s', args[0].text);164 test.verifyNull(cli.commandAssignment.value);165 args = cli._tokenize('tsv');166 cli._split(args);167 test.verifyEqual([], args);168 test.verifyEqual('tsv', cli.commandAssignment.value.name);169 args = cli._tokenize('tsv a b');170 cli._split(args);171 test.verifyEqual('tsv', cli.commandAssignment.value.name);172 test.verifyEqual(2, args.length);173 test.verifyEqual('a', args[0].text);174 test.verifyEqual('b', args[1].text);175 // TODO: add tests for sub commands176 return "testSplit Completed";177};178exports.testCli = function() {179 var assign1;180 var assign2;181 var cli = new CliRequisition();182 var debug = true;183 var worst;184 var display;185 var statuses;186 function update(input) {187 cli.update(input);188 if (debug) {189 console.log('####### TEST: typed="' + input.typed +190 '" cur=' + input.cursor.start +191 ' cli=', cli);192 }193 worst = cli.getWorstHint();194 display = cli.getAssignmentAt(input.cursor.start).getHint();195 statuses = cli.getInputStatusMarkup().map(function(status) {196 return status.valueOf();197 }).join('');198 if (cli.commandAssignment.value) {199 assign1 = cli.getAssignment(0);200 assign2 = cli.getAssignment(1);201 }202 else {203 assign1 = undefined;204 assign2 = undefined;205 }206 }207 function verifyPredictionsContains(name, predictions) {208 return predictions.every(function(prediction) {209 return name === prediction || name === prediction.name;210 }, this);211 }212 var historyLengthSetting = settings.getSetting('historyLength');213 update({ typed: '', cursor: { start: 0, end: 0 } });214 test.verifyEqual('', statuses);215 test.verifyEqual(Status.INCOMPLETE, display.status);216 test.verifyEqual(0, display.start);217 test.verifyEqual(0, display.end);218 test.verifyEqual(display, worst);219 test.verifyNull(cli.commandAssignment.value);220 update({ typed: ' ', cursor: { start: 1, end: 1 } });221 test.verifyEqual('0', statuses);222 test.verifyEqual(Status.INCOMPLETE, display.status);223 test.verifyEqual(1, display.start);224 test.verifyEqual(1, display.end);225 test.verifyEqual(display, worst);226 test.verifyNull(cli.commandAssignment.value);227 update({ typed: ' ', cursor: { start: 0, end: 0 } });228 test.verifyEqual('0', statuses);229 test.verifyEqual(Status.INCOMPLETE, display.status);230 test.verifyEqual(1, display.start);231 test.verifyEqual(1, display.end);232 test.verifyEqual(display, worst);233 test.verifyNull(cli.commandAssignment.value);234 update({ typed: 't', cursor: { start: 1, end: 1 } });235 test.verifyEqual('1', statuses);236 test.verifyEqual(Status.INCOMPLETE, display.status);237 test.verifyEqual(0, display.start);238 test.verifyEqual(1, display.end);239 test.verifyEqual(display, worst);240 test.verifyTrue(display.predictions.length > 0);241 test.verifyTrue(display.predictions.length < 20); // could break ...242 verifyPredictionsContains('tsv', display.predictions);243 verifyPredictionsContains('tsr', display.predictions);244 test.verifyNull(cli.commandAssignment.value);245 update({ typed: 'tsv', cursor: { start: 3, end: 3 } });246 test.verifyEqual('000', statuses);247 test.verifyEqual(Status.VALID, display.status);248 test.verifyEqual(-1, display.start);249 test.verifyEqual(-1, display.end);250 test.verifyEqual('tsv', cli.commandAssignment.value.name);251 update({ typed: 'tsv ', cursor: { start: 4, end: 4 } });252 test.verifyEqual('0000', statuses);253 test.verifyEqual(Status.VALID, display.status);254 test.verifyEqual(-1, display.start);255 test.verifyEqual(-1, display.end);256 test.verifyEqual('tsv', cli.commandAssignment.value.name);257 update({ typed: 'tsv ', cursor: { start: 2, end: 2 } });258 test.verifyEqual('0000', statuses);259 test.verifyEqual(Status.VALID, display.status);260 test.verifyEqual(0, display.start);261 test.verifyEqual(3, display.end);262 test.verifyEqual('tsv', cli.commandAssignment.value.name);263 update({ typed: 'tsv h', cursor: { start: 5, end: 5 } });264 test.verifyEqual('00001', statuses);265 test.verifyEqual(Status.INCOMPLETE, display.status);266 test.verifyEqual(4, display.start);267 test.verifyEqual(5, display.end);268 test.verifyTrue(display.predictions.length > 0);269 verifyPredictionsContains('historyLength', display.predictions);270 test.verifyEqual('tsv', cli.commandAssignment.value.name);271 test.verifyEqual('h', assign1.arg.text);272 test.verifyEqual(undefined, assign1.value);273 update({ typed: 'tsv historyLengt', cursor: { start: 16, end: 16 } });274 test.verifyEqual('0000111111111111', statuses);275 test.verifyEqual(Status.INCOMPLETE, display.status);276 test.verifyEqual(4, display.start);277 test.verifyEqual(16, display.end);278 test.verifyEqual(1, display.predictions.length);279 verifyPredictionsContains('historyLength', display.predictions);280 test.verifyEqual('tsv', cli.commandAssignment.value.name);281 test.verifyEqual('historyLengt', assign1.arg.text);282 test.verifyEqual(undefined, assign1.value);283 update({ typed: 'tsv historyLengt', cursor: { start: 1, end: 1 } });284 test.verifyEqual('0000222222222222', statuses);285 test.verifyEqual(Status.VALID, display.status);286 test.verifyEqual(0, display.start);287 test.verifyEqual(3, display.end);288 test.verifyEqual(Status.INVALID, worst.status);289 test.verifyEqual(4, worst.start);290 test.verifyEqual(16, worst.end);291 test.verifyEqual(1, worst.predictions.length);292 verifyPredictionsContains('historyLength', worst.predictions);293 test.verifyEqual('tsv', cli.commandAssignment.value.name);294 test.verifyEqual('historyLengt', assign1.arg.text);295 test.verifyEqual(undefined, assign1.value);296 update({ typed: 'tsv historyLengt ', cursor: { start: 17, end: 17 } });297 // TODO: would '00002222222222220' be better?298 test.verifyEqual('00002222222222222', statuses);299 test.verifyEqual(Status.VALID, display.status);300 test.verifyEqual(-1, display.start);301 test.verifyEqual(-1, display.end);302 test.verifyEqual(Status.INVALID, worst.status);303 test.verifyEqual(4, worst.start);304 test.verifyEqual(16, worst.end);305 test.verifyEqual(1, worst.predictions.length);306 verifyPredictionsContains('historyLength', worst.predictions);307 test.verifyEqual('tsv', cli.commandAssignment.value.name);308 test.verifyEqual('historyLengt', assign1.arg.text);309 test.verifyEqual(undefined, assign1.value);310 update({ typed: 'tsv historyLength', cursor: { start: 17, end: 17 } });311 test.verifyEqual('00000000000000000', statuses);312 test.verifyEqual('tsv', cli.commandAssignment.value.name);313 test.verifyEqual('historyLength', assign1.arg.text);314 test.verifyEqual(historyLengthSetting, assign1.value);315 update({ typed: 'tsv historyLength ', cursor: { start: 18, end: 18 } });316 test.verifyEqual('000000000000000000', statuses);317 test.verifyEqual('tsv', cli.commandAssignment.value.name);318 test.verifyEqual('historyLength', assign1.arg.text);319 test.verifyEqual(historyLengthSetting, assign1.value);320 update({ typed: 'tsv historyLength 6', cursor: { start: 19, end: 19 } });321 test.verifyEqual('0000000000000000000', statuses);322 test.verifyEqual('tsv', cli.commandAssignment.value.name);323 test.verifyEqual('historyLength', assign1.arg.text);324 test.verifyEqual(historyLengthSetting, assign1.value);325 test.verifyEqual('6', assign2.arg.text);326 test.verifyEqual(6, assign2.value);327 test.verifyEqual('number', typeof assign2.value);328 update({ typed: 'tsr', cursor: { start: 3, end: 3 } });329 test.verifyEqual('000', statuses);330 test.verifyEqual('tsr', cli.commandAssignment.value.name);331 test.verifyEqual(undefined, assign1.arg);332 test.verifyEqual(undefined, assign1.value);333 test.verifyEqual(undefined, assign2);334 update({ typed: 'tsr ', cursor: { start: 4, end: 4 } });335 test.verifyEqual('0000', statuses);336 test.verifyEqual('tsr', cli.commandAssignment.value.name);337 test.verifyEqual(undefined, assign1.arg);338 test.verifyEqual(undefined, assign1.value);339 test.verifyEqual(undefined, assign2);340 update({ typed: 'tsr h', cursor: { start: 5, end: 5 } });341 test.verifyEqual('00000', statuses);342 test.verifyEqual('tsr', cli.commandAssignment.value.name);343 test.verifyEqual('h', assign1.arg.text);344 test.verifyEqual('h', assign1.value);345 update({ typed: 'tsr "h h"', cursor: { start: 9, end: 9 } });346 test.verifyEqual('000000000', statuses);347 test.verifyEqual('tsr', cli.commandAssignment.value.name);348 test.verifyEqual('h h', assign1.arg.text);349 test.verifyEqual('h h', assign1.value);350 update({ typed: 'tsr h h h', cursor: { start: 9, end: 9 } });351 test.verifyEqual('000000000', statuses);352 test.verifyEqual('tsr', cli.commandAssignment.value.name);353 test.verifyEqual('h h h', assign1.arg.text);354 test.verifyEqual('h h h', assign1.value);355 // TODO: Add test to see that a command without mandatory param causes INVALID356 return "testCli Completed";357};...

Full Screen

Full Screen

gulpfile.js

Source:gulpfile.js Github

copy

Full Screen

1'use strict';2var fs = require( 'fs' );3var gulp = require( 'gulp' );4var gutil = require( 'gulp-util' );5var obj_verify = {6 vertices: [],7 normals: [],8 uvs: [],9 facesV: [],10 facesVn: [],11 facesVt: [],12 materials: []13};14obj_verify.vertices.push( [ -1, 1, 1 ] );15obj_verify.vertices.push( [ -1, -1, 1 ] );16obj_verify.vertices.push( [ 1, -1, 1 ] );17obj_verify.vertices.push( [ 1, 1, 1 ] );18obj_verify.vertices.push( [ -1, 1, -1 ] );19obj_verify.vertices.push( [ -1, -1, -1 ] );20obj_verify.vertices.push( [ 1, -1, -1 ] );21obj_verify.vertices.push( [ 1, 1, -1 ] );22obj_verify.normals.push( [ 0, 0, 1 ] );23obj_verify.normals.push( [ 0, 0, -1 ] );24obj_verify.normals.push( [ 0, 1, 0 ] );25obj_verify.normals.push( [ 0, -1, 0 ] );26obj_verify.normals.push( [ 1, 0, 0 ] );27obj_verify.normals.push( [ -1, 0, 0 ] );28obj_verify.uvs.push( [ 0, 1 ] );29obj_verify.uvs.push( [ 1, 1 ] );30obj_verify.uvs.push( [ 1, 0 ] );31obj_verify.uvs.push( [ 0, 0 ] );32obj_verify.facesV.push( [ 1, 2, 3, 4 ] );33obj_verify.facesV.push( [ 8, 7, 6, 5 ] );34obj_verify.facesV.push( [ 4, 3, 7, 8 ] );35obj_verify.facesV.push( [ 5, 1, 4, 8 ] );36obj_verify.facesV.push( [ 5, 6, 2, 1 ] );37obj_verify.facesV.push( [ 2, 6, 7, 3 ] );38obj_verify.facesVn.push( [ 1, 1, 1, 1 ] );39obj_verify.facesVn.push( [ 2, 2, 2, 2 ] );40obj_verify.facesVn.push( [ 5, 5, 5, 5 ] );41obj_verify.facesVn.push( [ 3, 3, 3, 3 ] );42obj_verify.facesVn.push( [ 6, 6, 6, 6 ] );43obj_verify.facesVn.push( [ 4, 4, 4, 4 ] );44obj_verify.facesVt.push( [ 1, 2, 3, 4 ] );45obj_verify.facesVt.push( [ 1, 2, 3, 4 ] );46obj_verify.facesVt.push( [ 1, 2, 3, 4 ] );47obj_verify.facesVt.push( [ 1, 2, 3, 4 ] );48obj_verify.facesVt.push( [ 1, 2, 3, 4 ] );49obj_verify.facesVt.push( [ 1, 2, 3, 4 ] );50obj_verify.materials.push( 'usemtl red' );51obj_verify.materials.push( 'usemtl blue' );52obj_verify.materials.push( 'usemtl green' );53obj_verify.materials.push( 'usemtl lightblue' );54obj_verify.materials.push( 'usemtl orange' );55obj_verify.materials.push( 'usemtl purple' );56function vobjCreateVertices( factor, offsets ) {57 var output = '\n';58 for ( var x, y, z, i = 0, v = obj_verify.vertices, length = v.length; i < length; i++ ) {59 x = v[ i ][ 0 ] * factor + offsets[ 0 ];60 y = v[ i ][ 1 ] * factor + offsets[ 1 ];61 z = v[ i ][ 2 ] * factor + offsets[ 2 ];62 output += 'v ' + x + ' ' + y + ' ' + z + '\n';63 }64 return output;65};66function vobjCreateUvs() {67 var output = '\n';68 for ( var x, y, z, i = 0, vn = obj_verify.uvs, length = vn.length; i < length; i++ ) {69 x = vn[ i ][ 0 ];70 y = vn[ i ][ 1 ];71 output += 'vt ' + x + ' ' + y + '\n';72 }73 return output;74};75function vobjCreateNormals() {76 var output = '\n';77 for ( var x, y, z, i = 0, vn = obj_verify.normals, length = vn.length; i < length; i++ ) {78 x = vn[ i ][ 0 ];79 y = vn[ i ][ 1 ];80 z = vn[ i ][ 2 ];81 output += 'vn ' + x + ' ' + y + ' ' + z + '\n';82 }83 return output;84};85function vobjCreateCubeV( offsets, groups, usemtls ) {86 var output = '\n';87 if ( groups === null || groups.length === 0 ) groups = [ null, null, null, null, null, null ];88 if ( usemtls === null || usemtls.length === 0 ) usemtls = [ null, null, null, null, null, null ];89 for ( var group, usemtl, f0, f1, f2, f3, i = 0, facesV = obj_verify.facesV, length = facesV.length; i < length; i++ ) {90 f0 = facesV[ i ][ 0 ] + offsets[ 0 ];91 f1 = facesV[ i ][ 1 ] + offsets[ 0 ];92 f2 = facesV[ i ][ 2 ] + offsets[ 0 ];93 f3 = facesV[ i ][ 3 ] + offsets[ 0 ];94 group = groups[ i ];95 usemtl = usemtls[ i ];96 if ( group ) output += 'g ' + group + '\n';97 if ( usemtl ) output += 'usemtl ' + usemtl + '\n';98 output += 'f ' + f0 + ' ' + f1 + ' ' + f2 + ' ' + f3 + '\n';99 }100 return output;101};102function vobjCreateCubeVVn( offsets, groups, usemtls ) {103 var output = '\n';104 if ( groups === null || groups.length === 0 ) groups = [ null, null, null, null, null, null ];105 if ( usemtls === null || usemtls.length === 0 ) usemtls = [ null, null, null, null, null, null ];106 for ( var group, usemtl, f0, f1, f2, f3, i = 0, facesV = obj_verify.facesV, facesVn = obj_verify.facesVn; i < 6; i++ ) {107 f0 = facesV[ i ][ 0 ] + offsets[ 0 ] + '//' + ( facesVn[ i ][ 0 ] + offsets[ 1 ] );108 f1 = facesV[ i ][ 1 ] + offsets[ 0 ] + '//' + ( facesVn[ i ][ 1 ] + offsets[ 1 ] );109 f2 = facesV[ i ][ 2 ] + offsets[ 0 ] + '//' + ( facesVn[ i ][ 2 ] + offsets[ 1 ] );110 f3 = facesV[ i ][ 3 ] + offsets[ 0 ] + '//' + ( facesVn[ i ][ 3 ] + offsets[ 1 ] );111 group = groups[ i ];112 usemtl = usemtls[ i ];113 if ( group ) output += 'g ' + group + '\n';114 if ( usemtl ) output += 'usemtl ' + usemtl + '\n';115 output += 'f ' + f0 + ' ' + f1 + ' ' + f2 + ' ' + f3 + '\n';116 }117 return output;118};119function vobjCreateCubeVVt( offsets, groups, usemtls ) {120 var output = '\n';121 if ( groups === null || groups.length === 0 ) groups = [ null, null, null, null, null, null ];122 if ( usemtls === null || usemtls.length === 0 ) usemtls = [ null, null, null, null, null, null ];123 for ( var group, usemtl, f0, f1, f2, f3, i = 0, facesV = obj_verify.facesV, facesVt = obj_verify.facesVt; i < 6; i++ ) {124 f0 = facesV[ i ][ 0 ] + offsets[ 0 ] + '/' + ( facesVt[ i ][ 0 ] + offsets[ 1 ] );125 f1 = facesV[ i ][ 1 ] + offsets[ 0 ] + '/' + ( facesVt[ i ][ 1 ] + offsets[ 1 ] );126 f2 = facesV[ i ][ 2 ] + offsets[ 0 ] + '/' + ( facesVt[ i ][ 2 ] + offsets[ 1 ] );127 f3 = facesV[ i ][ 3 ] + offsets[ 0 ] + '/' + ( facesVt[ i ][ 3 ] + offsets[ 1 ] );128 group = groups[ i ];129 usemtl = usemtls[ i ];130 if ( group ) output += 'g ' + group + '\n';131 if ( usemtl ) output += 'usemtl ' + usemtl + '\n';132 output += 'f ' + f0 + ' ' + f1 + ' ' + f2 + ' ' + f3 + '\n';133 }134 return output;135};136function vobjCreateCubeVVnVt( offsets, groups, usemtls ) {137 var output = '\n';138 if ( groups === null || groups.length === 0 ) groups = [ null, null, null, null, null, null ];139 if ( usemtls === null || usemtls.length === 0 ) usemtls = [ null, null, null, null, null, null ];140 for ( var group, usemtl, f0, f1, f2, f3, i = 0, facesV = obj_verify.facesV, facesVt = obj_verify.facesVt, facesVn = obj_verify.facesVn; i < 6; i++ ) {141 f0 = facesV[ i ][ 0 ] + offsets[ 0 ] + '/' + ( facesVt[ i ][ 0 ] + offsets[ 1 ] ) + '/' + ( facesVn[ i ][ 0 ] + offsets[ 2 ] );142 f1 = facesV[ i ][ 1 ] + offsets[ 0 ] + '/' + ( facesVt[ i ][ 1 ] + offsets[ 1 ] ) + '/' + ( facesVn[ i ][ 1 ] + offsets[ 2 ] );143 f2 = facesV[ i ][ 2 ] + offsets[ 0 ] + '/' + ( facesVt[ i ][ 2 ] + offsets[ 1 ] ) + '/' + ( facesVn[ i ][ 2 ] + offsets[ 2 ] );144 f3 = facesV[ i ][ 3 ] + offsets[ 0 ] + '/' + ( facesVt[ i ][ 3 ] + offsets[ 1 ] ) + '/' + ( facesVn[ i ][ 3 ] + offsets[ 2 ] );145 group = groups[ i ];146 usemtl = usemtls[ i ];147 if ( group ) output += 'g ' + group + '\n';148 if ( usemtl ) output += 'usemtl ' + usemtl + '\n';149 output += 'f ' + f0 + ' ' + f1 + ' ' + f2 + ' ' + f3 + '\n';150 }151 return output;152};153gulp.task( 'default', function( cb ){154 gutil.log( 'Building: verify.obj' );155 var offsets = [ 0, 0, 0 ];156 var pos = [ -150, 50, 0 ];157 fs.writeFileSync( './verify.obj', '# Verification OBJ created with gulp\n\n' );158 fs.appendFileSync( './verify.obj', 'mtllib verify.mtl\n\n# Cube no materials. Translated x:' + pos[ 0 ] );159 fs.appendFileSync( './verify.obj', vobjCreateVertices( 10, pos ) );160 fs.appendFileSync( './verify.obj', vobjCreateCubeV( offsets, null, null ) );161 pos[ 0 ] += 50;162 offsets[ 0 ] += 8;163 fs.appendFileSync( './verify.obj', '\n\n# Cube with two materials. Translated x:' + pos[ 0 ] );164 fs.appendFileSync( './verify.obj', vobjCreateVertices( 10, pos ) );165 fs.appendFileSync( './verify.obj', vobjCreateCubeV( offsets, null, [ 'orange', null, null, 'purple', null, null ] ) );166 pos[ 0 ] += 50;167 offsets[ 0 ] += 8;168 fs.appendFileSync( './verify.obj', '\n\n# Cube with normals no materials. Translated x:' + pos[ 0 ] );169 fs.appendFileSync( './verify.obj', vobjCreateVertices( 10, pos ) );170 fs.appendFileSync( './verify.obj', vobjCreateNormals() );171 fs.appendFileSync( './verify.obj', vobjCreateCubeVVn( offsets, [ 'cube3', null, null, null, null, null ], [ 'lightblue', null, null, null, null, null ] ) );172 pos[ 0 ] += 50;173 offsets[ 0 ] += 8;174 fs.appendFileSync( './verify.obj', '\n\n# Cube with uvs and red material. Translated x:' + pos[ 0 ] );175 fs.appendFileSync( './verify.obj', vobjCreateVertices( 10, pos ) );176 fs.appendFileSync( './verify.obj', vobjCreateUvs() );177 fs.appendFileSync( './verify.obj', vobjCreateCubeVVt( offsets, null, [ 'red', null, null, null, null, null ] ) );178 pos[ 0 ] += 50;179 offsets[ 0 ] += 8;180 fs.appendFileSync( './verify.obj', '\n\n# cube with uvs and normals and material. Translated x' + pos[ 0 ] );181 fs.appendFileSync( './verify.obj', vobjCreateVertices( 10, pos ) );182 fs.appendFileSync( './verify.obj', vobjCreateCubeVVnVt( offsets, [], [ 'red', null, null, 'blue', null, 'green' ] ) );183 pos[ 0 ] += 50;184 offsets[ 0 ] += 8;185 offsets[ 1 ] += 6;186 fs.appendFileSync( './verify.obj', '\n\n# cube with uvs and normals and two materials and group for every quad. Translated x:' + pos[ 0 ] );187 fs.appendFileSync( './verify.obj', vobjCreateVertices( 10, pos ) );188 fs.appendFileSync( './verify.obj', vobjCreateNormals() );189 fs.appendFileSync( './verify.obj', vobjCreateCubeVVnVt( [ -9, offsets[ 1 ], offsets[ 2 ] ],190 [ 'cube6a', 'cube6b', 'cube6c', 'cube6d', 'cube6e', 'cube6f' ],191 [ 'green', null, null, 'orange', null, null ] ) );192 pos[ 0 ] += 50;193 offsets[ 0 ] += 8;194 fs.appendFileSync( './verify.obj', '\n\n# cube with uvs and normals and six materials and six groups, one for every quad. Translated x:' + pos[ 0 ] );195 fs.appendFileSync( './verify.obj', vobjCreateVertices( 10, pos ) );196 fs.appendFileSync( './verify.obj', vobjCreateCubeVVnVt( offsets,197 [ 'cube6a', 'cube6b', 'cube6c', 'cube6d', 'cube6e', 'cube6f' ],198 [ 'red', 'blue', 'green', 'lightblue', 'orange', 'purple' ] ) );199 pos[ 0 ] += 50;200 offsets[ 0 ] += 8;201 fs.appendFileSync( './verify.obj', '\n\n# Point. Translated x:' + pos[ 0 ] );202 fs.appendFileSync( './verify.obj', vobjCreateVertices( 10, pos ) );203 fs.appendFileSync( './verify.obj', '\np -8 -7 -6 -5 -4 -3 -2 -1\n' );204 pos[ 0 ] += 50;205 offsets[ 0 ] += 8;206 fs.appendFileSync( './verify.obj', '\n\n# Line. Translated x:' + pos[ 0 ] );207 fs.appendFileSync( './verify.obj', vobjCreateVertices( 10, pos ) );208 fs.appendFileSync( './verify.obj', 'l -8 -7 -6 -5 -4 -3 -2 -1 -8 -5 -8 -4 -7 -6 -7 -3 -5 -1 -3 -2 -6 -2 -4 -1\n' );209 pos[ 0 ] += 50;210 offsets[ 0 ] += 8;211 fs.appendFileSync( './verify.obj', '\n\n# Line UV. Translated x:' + pos[ 0 ] );212 fs.appendFileSync( './verify.obj', vobjCreateVertices( 10, pos ) );213 fs.appendFileSync( './verify.obj', '\nl -8/-2 -7/-1 -6/-2 -5/-1\n' );...

Full Screen

Full Screen

test-ui.py

Source:test-ui.py Github

copy

Full Screen

1#!/usr/bin/env python2import linuxcnc3import hal4import time5import sys6import os7# this is how long we wait for linuxcnc to do our bidding8timeout = 1.09def introspect():10 os.system("halcmd show pin python-ui")11def wait_for_pin_value(pin_name, value, timeout=1):12 print "waiting for %s to go to %f (timeout=%f)" % (pin_name, value, timeout)13 start = time.time()14 while (h[pin_name] != value) and ((time.time() - start) < timeout):15 time.sleep(0.1)16 if h[pin_name] != value:17 print "timeout! pin %s is %f, didn't get to %f" % (pin_name, h[pin_name], value)18 introspect()19 sys.exit(1)20 print "pin %s went to %f!" % (pin_name, value)21def verify_pin_value(pin_name, value):22 if (h[pin_name] != value):23 print "pin %s is %f, not %f" % (pin_name, h[pin_name], value)24 sys.exit(1);25 print "pin %s is %f" % (pin_name, value)26def get_interp_param(param_number):27 c.mdi("(debug, #%d)" % param_number)28 c.wait_complete()29 # wait up to 2 seconds for a reply30 start = time.time()31 while (time.time() - start) < 2:32 error = e.poll()33 if error == None:34 time.sleep(0.010)35 continue36 kind, text = error37 if kind == linuxcnc.OPERATOR_DISPLAY:38 return float(text)39 print text40 print "error getting parameter %d" % param_number41 return None42def verify_interp_param(param_number, expected_value):43 param_value = get_interp_param(param_number)44 print "interp param #%d = %f (expecting %f)" % (param_number, param_value, expected_value)45 if param_value != expected_value:46 print "ERROR: interp param #%d = %f, expected %f" % (param_number, param_value, expected_value)47 sys.exit(1)48def verify_stable_pin_values(pins, duration=1):49 start = time.time()50 while (time.time() - start) < duration:51 for pin_name in pins.keys():52 val = h[pin_name]53 if val != pins[pin_name]:54 print "ERROR: pin %s = %f (expected %f)" % (pin_name, val, pin[pin_name])55 sys.exit(1)56 time.sleep(0.010)57def verify_tool_number(tool_number):58 verify_interp_param(5400, tool_number) # 5400 == tool in spindle59 verify_pin_value('tool-number', tool_number) # pin from iocontrol60 # verify stat buffer61 s.poll()62 if s.tool_in_spindle != tool_number:63 print "ERROR: stat buffer .tool_in_spindle is %f, should be %f" % (s.tool_in_spindle, tool_number)64 sys.exit(1)65 print "stat buffer .tool_in_spindle is %f" % s.tool_in_spindle66def do_tool_change_handshake(tool_number, pocket_number):67 # prepare for tool change68 wait_for_pin_value('tool-prepare', 1)69 verify_pin_value('tool-prep-number', tool_number)70 verify_pin_value('tool-prep-pocket', pocket_number)71 h['tool-prepared'] = 172 wait_for_pin_value('tool-prepare', 0)73 h['tool-prepared'] = 074 time.sleep(0.1)75 s.poll()76 print "tool prepare done, s.pocket_prepped = ", s.pocket_prepped77 if s.pocket_prepped != pocket_number:78 print "ERROR: wrong pocket prepped in stat buffer (got %d, expected %d)" % (s.pocket_prepped, pocket_number)79 sys.exit(1)80 # change tool81 wait_for_pin_value('tool-change', 1)82 h['tool-changed'] = 183 wait_for_pin_value('tool-change', 0)84 h['tool-changed'] = 085#86# set up pins87# shell out to halcmd to net our pins to where they need to go88#89h = hal.component("python-ui")90h.newpin("tool-number", hal.HAL_S32, hal.HAL_IN)91h.newpin("tool-prep-number", hal.HAL_S32, hal.HAL_IN)92h.newpin("tool-prep-pocket", hal.HAL_S32, hal.HAL_IN)93h.newpin("tool-prepare", hal.HAL_BIT, hal.HAL_IN)94h.newpin("tool-prepared", hal.HAL_BIT, hal.HAL_OUT)95h.newpin("tool-change", hal.HAL_BIT, hal.HAL_IN)96h.newpin("tool-changed", hal.HAL_BIT, hal.HAL_OUT)97h.ready() # mark the component as 'ready'98os.system("halcmd source ./postgui.hal")99#100# connect to LinuxCNC101#102c = linuxcnc.command()103s = linuxcnc.stat()104e = linuxcnc.error_channel()105c.state(linuxcnc.STATE_ESTOP_RESET)106c.state(linuxcnc.STATE_ON)107c.mode(linuxcnc.MODE_MDI)108c.wait_complete()109# at startup, we should have the special tool 0 in the spindle, meaning110# "no tool" or "unknown tool"111verify_tool_number(0)112#113# test m6 to get a baseline114#115print "*** starting 'T1 M6' tool change"116c.mdi('t1 m6')117c.wait_complete()118do_tool_change_handshake(tool_number=1, pocket_number=1)119print "*** tool change complete"120verify_tool_number(1)121verify_interp_param(5401, 0) # tlo x122verify_interp_param(5402, 0) # tlo y123verify_interp_param(5403, 1) # tlo z124verify_interp_param(5404, 0) # tlo a125verify_interp_param(5405, 0) # tlo b126verify_interp_param(5406, 0) # tlo c127verify_interp_param(5407, 0) # tlo u128verify_interp_param(5408, 0) # tlo v129verify_interp_param(5409, 0) # tlo w130verify_interp_param(5410, 0.125) # tool diameter131verify_interp_param(5411, 0) # front angle132verify_interp_param(5412, 0) # back angle133verify_interp_param(5413, 0) # tool orientation134verify_interp_param(5420, 0) # current x135verify_interp_param(5421, 0) # current y136verify_interp_param(5422, 0) # current z137verify_interp_param(5423, 0) # current a138verify_interp_param(5424, 0) # current b139verify_interp_param(5425, 0) # current c140verify_interp_param(5426, 0) # current u141verify_interp_param(5427, 0) # current v142verify_interp_param(5428, 0) # current w143c.mdi('g43')144c.wait_complete()145verify_interp_param(5420, 0) # current x146verify_interp_param(5421, 0) # current y147verify_interp_param(5422, -1) # current z148verify_interp_param(5423, 0) # current a149verify_interp_param(5424, 0) # current b150verify_interp_param(5425, 0) # current c151verify_interp_param(5426, 0) # current u152verify_interp_param(5427, 0) # current v153verify_interp_param(5428, 0) # current w154introspect()155#156# now finally test m61157#158print "*** starting 'M61 Q10' tool change"159c.mdi('m61 q10')160c.wait_complete()161verify_stable_pin_values(162 {163 'tool-change': 0,164 'tool-prep-number': 0,165 'tool-prep-pocket': 0,166 'tool-prepare': 0167 },168 duration=1169)170verify_tool_number(10)171verify_interp_param(5401, 0) # tlo x172verify_interp_param(5402, 0) # tlo y173verify_interp_param(5403, 3) # tlo z174verify_interp_param(5404, 0) # tlo a175verify_interp_param(5405, 0) # tlo b176verify_interp_param(5406, 0) # tlo c177verify_interp_param(5407, 0) # tlo u178verify_interp_param(5408, 0) # tlo v179verify_interp_param(5409, 0) # tlo w180verify_interp_param(5410, 0.500) # tool diameter181verify_interp_param(5411, 0) # front angle182verify_interp_param(5412, 0) # back angle183verify_interp_param(5413, 0) # tool orientation184verify_interp_param(5420, 0) # current x185verify_interp_param(5421, 0) # current y186verify_interp_param(5422, -1) # current z187verify_interp_param(5423, 0) # current a188verify_interp_param(5424, 0) # current b189verify_interp_param(5425, 0) # current c190verify_interp_param(5426, 0) # current u191verify_interp_param(5427, 0) # current v192verify_interp_param(5428, 0) # current w193c.mdi('g43')194c.wait_complete()195verify_interp_param(5420, 0) # current x196verify_interp_param(5421, 0) # current y197verify_interp_param(5422, -3) # current z198verify_interp_param(5423, 0) # current a199verify_interp_param(5424, 0) # current b200verify_interp_param(5425, 0) # current c201verify_interp_param(5426, 0) # current u202verify_interp_param(5427, 0) # current v203verify_interp_param(5428, 0) # current w204#205# use M6 to unload the spindle (T0)206#207print "*** using 'T0 M6' to unload the spindle"208c.mdi("t0 m6")209c.wait_complete()210do_tool_change_handshake(tool_number=0, pocket_number=0)211verify_tool_number(0)212#213# use M61 to load T1 in the spindle again214#215print "*** using 'M61 Q1' to load a tool again"216c.mdi("m61 q1")217c.wait_complete()218verify_tool_number(1)219#220# use M61 to unload the spindle (T0)221#222print "*** using 'M61 Q0' to unload the spindle again"223c.mdi("m61 q0")224c.wait_complete()225verify_tool_number(0)226# if we get here it all worked!...

Full Screen

Full Screen

safety.js

Source:safety.js Github

copy

Full Screen

1$(function()2{3 $verify_win = $('#verify-win');4 // 原帐号验证码发送5 $('.verify-submit, .verify-submit-win').on('click', function()6 {7 var $this = $(this);8 var $verify = $('#verify-img-value');9 var verify = '';10 // 是否需要先校验图片验证码11 if($this.data('verify') == 1)12 {13 // 开启图片验证码窗口14 $verify_win.modal('open');15 $verify.focus();16 return false;17 }18 // 验证码窗口操作按钮则更新按钮对象19 var is_win = $(this).data('win');20 if(is_win == 1)21 {22 $this = $('.verify-submit');23 // 验证码参数处理24 verify = $verify.val().replace(/\s+/g, '');25 if(verify.length < 6)26 {27 Prompt($verify.data('validation-message'));28 $verify.focus();29 return false;30 }31 }32 // 验证码时间间隔33 var time_count = parseInt($this.data('time'));34 35 // 按钮交互36 $this.button('loading');37 if(is_win == 1)38 {39 $('.verify-submit-win').button('loading');40 }41 // 发送验证码42 $.ajax({43 url:$('.verify-submit').data('url'),44 type:'POST',45 data:{"verify":verify, "type":$('form input[name="type"]').val()},46 dataType:'json',47 success:function(result)48 {49 if(result.code == 0)50 {51 var intervalid = setInterval(function()52 {53 if(time_count == 0)54 {55 $this.button('reset');56 if(is_win == 1)57 {58 $('.verify-submit-win').button('reset');59 }60 $this.text($this.data('text'));61 $verify.val('');62 clearInterval(intervalid);63 } else {64 var send_msg = $this.data('send-text').replace(/{time}/, time_count--);65 $this.text(send_msg);66 }67 }, 1000);68 $verify_win.modal('close');69 } else {70 $this.button('reset');71 if(is_win == 1)72 {73 $('.verify-submit-win').button('reset');74 }75 Prompt(result.msg);76 }77 },78 error:function()79 {80 $this.button('reset');81 if(is_win == 1)82 {83 $('.verify-submit-win').button('reset');84 }85 Prompt('网络错误');86 }87 });88 });89 // 新帐号验证码获取90 $('.verify-submit-new, .verify-submit-win-new').on('click', function()91 {92 var $this = $(this);93 var $accounts = $('#accounts');94 var $verify = $('#verify-img-value');95 var verify = '';96 if($accounts.hasClass('am-field-valid'))97 {98 // 是否需要先校验图片验证码99 if($this.data('verify') == 1)100 {101 // 开启图片验证码窗口102 $verify_win.modal('open');103 $verify.focus();104 return false;105 }106 // 验证码窗口操作按钮则更新按钮对象107 var is_win = $(this).data('win');108 if(is_win == 1)109 {110 $this = $('.verify-submit-new');111 // 验证码参数处理112 verify = $verify.val().replace(/\s+/g, '');113 if(verify.length < 6)114 {115 Prompt($verify.data('validation-message'));116 $verify.focus();117 return false;118 }119 }120 // 验证码时间间隔121 var time_count = parseInt($this.data('time'));122 123 // 按钮交互124 $this.button('loading');125 if(is_win == 1)126 {127 $('.verify-submit-win-new').button('loading');128 }129 // 发送验证码130 $.ajax({131 url:$('.verify-submit-new').data('url'),132 type:'POST',133 data:{"accounts":$accounts.val(), "verify":verify, "type":$('form input[name="type"]').val()},134 dataType:'json',135 success:function(result)136 {137 if(result.code == 0)138 {139 var intervalid = setInterval(function()140 {141 if(time_count == 0)142 {143 $this.button('reset');144 if(is_win == 1)145 {146 $('.verify-submit-win-new').button('reset');147 }148 $this.text($this.data('text'));149 $verify.val('');150 clearInterval(intervalid);151 } else {152 var send_msg = $this.data('send-text').replace(/{time}/, time_count--);153 $this.text(send_msg);154 }155 }, 1000);156 $verify_win.modal('close');157 } else {158 $this.button('reset');159 if(is_win == 1)160 {161 $('.verify-submit-win-new').button('reset');162 }163 Prompt(result.msg);164 }165 },166 error:function()167 {168 $this.button('reset');169 if(is_win == 1)170 {171 $('.verify-submit-win-new').button('reset');172 }173 Prompt('网络错误');174 }175 }); 176 } else {177 $verify_win.modal('close');178 $accounts.focus();179 }180 });...

Full Screen

Full Screen

credential.py

Source:credential.py Github

copy

Full Screen

...47 )48 and len(header) == 349 ):50 raise Exception("Invalid JWS header parameters for Ed25519Signature2018.")51async def jws_verify(verify_data, signature, public_key, wallet):52 """Detatched jws verify handling."""53 encoded_header, _, encoded_signature = signature.partition("..")54 decoded_header = json.loads(b64decode(encoded_header))55 verify_jws_header(decoded_header)56 decoded_signature = b64_to_bytes(encoded_signature, urlsafe=True)57 jws_to_verify = create_jws(encoded_header, verify_data)58 verified = await wallet.verify_message(jws_to_verify, decoded_signature, public_key)59 return verified60async def sign_credential(credential, signature_options, verkey, wallet):61 """Sign Credential."""62 framed, verify_data_hex_string = create_verify_data(credential, signature_options)63 verify_data_bytes = bytes.fromhex(verify_data_hex_string)64 jws = await jws_sign(verify_data_bytes, verkey, wallet)65 document_with_proof = {**credential, "proof": {**signature_options, "jws": jws}}66 return document_with_proof67async def verify_credential(doc, verkey, wallet):68 """Verify credential."""69 framed, verify_data_hex_string = create_verify_data(doc, doc["proof"])70 verify_data_bytes = bytes.fromhex(verify_data_hex_string)71 valid = await jws_verify(verify_data_bytes, framed["proof"]["jws"], verkey, wallet)...

Full Screen

Full Screen

colors.js

Source:colors.js Github

copy

Full Screen

1define(["doh/main", "../_base/array", "../_base/Color", "../colors"], function(doh, array, Color, colors){2 var verifyColor = function(t, source, expected){3 source = new Color(source);4 expected = new Color(expected);5 t.is(expected.toRgba(), source.toRgba());6 array.forEach(source.toRgba(), function(n){ t.is("number", typeof(n)); });7 };8 doh.register("tests.colors", [9 // all tests below are taken from #4.2 of the CSS3 Color Module10 function testColorEx01(t){ verifyColor(t, "black", [0, 0, 0]); },11 function testColorEx02(t){ verifyColor(t, "white", [255, 255, 255]); },12 function testColorEx03(t){ verifyColor(t, "maroon", [128, 0, 0]); },13 function testColorEx04(t){ verifyColor(t, "olive", [128, 128, 0]); },14 function testColorEx05(t){ verifyColor(t, "#f00", "red"); },15 function testColorEx06(t){ verifyColor(t, "#ff0000", "red"); },16 function testColorEx07(t){ verifyColor(t, "rgb(255, 0, 0)", "red"); },17 function testColorEx08(t){ verifyColor(t, "rgb(100%, 0%, 0%)", "red"); },18 function testColorEx09(t){ verifyColor(t, "rgb(300, 0, 0)", "red"); },19 function testColorEx10(t){ verifyColor(t, "rgb(255, -10, 0)", "red"); },20 function testColorEx11(t){ verifyColor(t, "rgb(110%, 0%, 0%)", "red"); },21 function testColorEx12(t){ verifyColor(t, "rgba(255, 0, 0, 1)", "red"); },22 function testColorEx13(t){ verifyColor(t, "rgba(100%, 0%, 0%, 1)", "red"); },23 function testColorEx14(t){ verifyColor(t, "rgba(0, 0, 255, 0.5)", [0, 0, 255, 0.5]); },24 function testColorEx15(t){ verifyColor(t, "rgba(100%, 50%, 0%, 0.1)", [255, 128, 0, 0.1]); },25 function testColorEx16(t){ verifyColor(t, "hsl(0, 100%, 50%)", "red"); },26 function testColorEx17(t){ verifyColor(t, "hsl(120, 100%, 50%)", "lime"); },27 function testColorEx18(t){ verifyColor(t, "hsl(120, 100%, 25%)", "green"); },28 function testColorEx19(t){ verifyColor(t, "hsl(120, 100%, 75%)", "#80ff80"); },29 function testColorEx20(t){ verifyColor(t, "hsl(120, 50%, 50%)", "#40c040"); },30 function testColorEx21(t){ verifyColor(t, "hsla(120, 100%, 50%, 1)", "lime"); },31 function testColorEx22(t){ verifyColor(t, "hsla(240, 100%, 50%, 0.5)", [0, 0, 255, 0.5]); },32 function testColorEx23(t){ verifyColor(t, "hsla(30, 100%, 50%, 0.1)", [255, 128, 0, 0.1]); },33 function testColorEx24(t){ verifyColor(t, "transparent", [0, 0, 0, 0]); },34 // all tests below test greyscale colors35 function testColorEx25(t){ verifyColor(t, colors.makeGrey(5), [5, 5, 5, 1]); },36 function testColorEx26(t){ verifyColor(t, colors.makeGrey(2, 0.3), [2, 2, 2, 0.3]); }37 ]);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { Verifier } = require('@pact-foundation/pact');2const path = require('path');3const opts = {4 pactUrls: [path.resolve(process.cwd(), 'pacts', 'test1-test2.json')],5};6Verifier.verifyProvider(opts)7 .then(output => {8 console.log('Pact Verification Complete!');9 console.log(output);10 })11 .catch(e => {12 console.log('Pact Verification Failed: ', e);13 });14const { Verifier } = require('@pact-foundation/pact');15const path = require('path');16const opts = {17 pactUrls: [path.resolve(process.cwd(), 'pacts', 'test1-test2.json')],18};19Verifier.verifyProvider(opts)20 .then(output => {21 console.log('Pact Verification Complete!');22 console.log(output);23 })24 .catch(e => {25 console.log('Pact Verification Failed: ', e);26 });27 Failure/Error: expect(response.status).to eq 20028 (compared using ==)

Full Screen

Using AI Code Generation

copy

Full Screen

1var pact = require('pact-foundation-pact-web');2var path = require('path');3var opts = {4 pactUrls: [path.resolve(__dirname, 'pacts', 'test1-test2.json')]5};6pact.verifyPacts(opts).then(function () {7 console.log('success');8}).catch(function (err) {9 console.log('error', err);10});11{12 "headers": {13 },14}15{16 "consumer": {17 },18 "provider": {19 },20 {21 "request": {22 "headers": {23 },24 },25 "response": {26 "headers": {27 },28 "body": {29 }30 }31 }32 "metadata": {33 "pactSpecification": {34 }35 }36}

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run pact-foundation-pact automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful