diff python/testparserlib.py @ 212:62386bcee1ba

Added parser combinator lib
author Windel Bouwman
date Sun, 30 Jun 2013 19:00:41 +0200
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/python/testparserlib.py	Sun Jun 30 19:00:41 2013 +0200
@@ -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()
+