summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--pyparsing/core.py5
-rw-r--r--tests/test_unit.py31
2 files changed, 35 insertions, 1 deletions
diff --git a/pyparsing/core.py b/pyparsing/core.py
index f24369c..dec64c7 100644
--- a/pyparsing/core.py
+++ b/pyparsing/core.py
@@ -4543,9 +4543,12 @@ class OnlyOnce:
results = self.callable(s, l, t)
self.called = True
return results
- raise ParseException(s, l, "")
+ raise ParseException(s, l, "OnlyOnce obj called multiple times w/out reset")
def reset(self):
+ """Allow the associated parse action to be called once more.
+ """
+
self.called = False
diff --git a/tests/test_unit.py b/tests/test_unit.py
index d7bb77d..a2a5580 100644
--- a/tests/test_unit.py
+++ b/tests/test_unit.py
@@ -7087,6 +7087,37 @@ class Test2_WithoutPackrat(ppt.TestParseResultsAsserts, TestCase):
exprWithInt, "rucksack 49", {"item": "rucksack", "qty": 49}
)
+ def testOnlyOnce(self):
+ """test class OnlyOnce and its reset method"""
+
+ # use a parse action to compute the sum of the parsed integers,
+ # and add it to the end
+ def append_sum(tokens):
+ tokens.append(sum(map(int, tokens)))
+
+ pa = pp.OnlyOnce(append_sum)
+ expr = pp.OneOrMore(pp.Word(pp.nums)).addParseAction(pa)
+
+ result = expr.parseString("0 123 321")
+ print(result.dump())
+ expected = ["0", "123", "321", 444]
+ self.assertParseResultsEquals(
+ result, expected, msg="issue with OnlyOnce first call"
+ )
+
+ with self.assertRaisesParseException(
+ msg="failed to raise exception calling OnlyOnce more than once"
+ ):
+ result2 = expr.parseString("1 2 3 4 5")
+
+ pa.reset()
+ result = expr.parseString("100 200 300")
+ print(result.dump())
+ expected = ["100", "200", "300", 600]
+ self.assertParseResultsEquals(
+ result, expected, msg="issue with OnlyOnce after reset"
+ )
+
class Test3_EnablePackratParsing(TestCase):
def runTest(self):