diff test/testparserlib.py @ 284:05184b95fa16

Moved tests to seperate folder
author Windel Bouwman
date Fri, 15 Nov 2013 13:43:22 +0100
parents python/testparserlib.py@62386bcee1ba
children 6753763d3bec
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/testparserlib.py	Fri Nov 15 13:43:22 2013 +0100
@@ -0,0 +1,61 @@
+import unittest
+from parserlib import OneOrMore, Literal, Or, Sequence, Optional
+
+class ParserCombinatorTestCase(unittest.TestCase):
+    def test1(self):
+        #p = Parser()
+        # parse and interpret:
+        n40 = Literal('40')
+        plus = Literal('+')
+        n2 = Literal('2')
+        n40.ParseAction = int
+        plus.ParseAction = replaceWith(0)
+        n2.ParseAction = int
+        p = Sequence([n40,plus,n2])
+        p.ParseAction = wordsum
+
+        result = p.parse('40+2')
+        self.assertEqual(42, result[0])
+
+def replaceWith(s):
+    def _repFunc(*args):
+        return s
+    return _repFunc
+
+wordsum = lambda t: sum(t)
+
+class WordToNumTestCase(unittest.TestCase):
+    def setUp(self):
+        numWords = OneOrMore()
+        def makeLit(s, val):
+            ret = Literal(s)
+            ret.ParseAction = replaceWith(val)
+            return ret
+        unitDefs = [('zero', 0), ('three', 3), ('one', 1)]
+        units = Or( [makeLit(s, v) for s, v in unitDefs] )
+        tensDefs = [('twenty', 20)]
+        tens = Or( [makeLit(s, v) for s, v in tensDefs] )
+
+        numPart = Sequence([Optional(tens), units])
+        numPart.ParseAction = wordsum
+        self.p = numPart
+
+    def check(self, i, o):
+        result = self.p.parse(i)[0]
+        self.assertEqual(o, result)
+
+    def test0(self):
+        self.check('zero', 0)
+        
+    def test23(self):
+        self.check('twentythree', 23)
+
+    @unittest.skip
+    def test321(self):
+        # TODO
+        self.check('three hundred and twenty one', 321)
+        
+
+if __name__ == '__main__':
+    unittest.main()
+