Search code examples
unit-testingpyparsing

How to assert a pyparsing.ParseResults content?


I would like to validate using Python assert on the pyparsing.ParseResults class and its content.

A working snippet of Python pyparsing code is given here:

import pyparsing as pp
first = pp.Word(pp.srange('[a-zA-Z]'), exact=1)
rest = pp.Optional(pp.Word(pp.srange('[_0-9a-zA-Zz]')))
keyName = pp.Combine(first + rest)

A simple printout is (and gets misleading):

print keyName.parseString("Abc_de")
['Abc_de']
#
print ['Abc_de']
['Abc_de']

Of course, the following assert fails:

# Unit test that is faulty
assert keyName.parseString("Abc_de") == ['Abc_de']

Unit test is failing... because the type of ['Abc_de'] is a list whereas the type of keyName.parseString("Abc_de")) is a <class 'pyparsing.ParseResults'>.

What method should I be calling so that assertion can easily be made?


Solution

  • Use the asList method on the result returned by parseString.

    import pyparsing as pp
    first = pp.Word(pp.srange('[a-zA-Z]'), exact=1)
    rest = pp.Optional(pp.Word(pp.srange('[_0-9a-zA-Zz]')))
    keyName = pp.Combine(first + rest)
    
    assert keyName.parseString('Abc_de').asList() == ['Abc_de']