view python/testparserlib.py @ 281:4496cae24d7f

Improved logview
author Windel Bouwman
date Sat, 02 Nov 2013 11:11:40 +0100
parents 62386bcee1ba
children
line wrap: on
line source

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()