diff --git a/tests/textfsm_test.py b/tests/textfsm_test.py index 9177e56..11939ed 100755 --- a/tests/textfsm_test.py +++ b/tests/textfsm_test.py @@ -749,6 +749,58 @@ def testList(self): result = t.ParseText(data) self.assertListEqual(result, [[['one'], 'two']]) + def testAlternationWithoutValueGroup(self): + """A rule matching via a branch without the value group keeps the value. + + Rules may contain alternations where the value's named group does not + participate in the matched branch. Assigning None in that case appends + None to List values and overwrites Filldown memory. + """ + + # List values do not accumulate None when the group does not match. + tplt = ( + 'Value List boo (on.)\n' + 'Value hoo (tw.)\n\n' + 'Start\n' + ' ^$boo\n' + ' ^$boo|zz -> Next.Record\n' + ) + + t = textfsm.TextFSM(io.StringIO(tplt)) + result = t.ParseText('one\nzz') + self.assertListEqual(result, [[['one'], '']]) + + # An optional value group that did not participate leaves the + # value unchanged. + tplt = ( + 'Value boo (on.)\n' + 'Value List hoo (tw.)\n\n' + 'Start\n' + ' ^${boo}(${hoo})? -> Next.Record\n' + ) + + t = textfsm.TextFSM(io.StringIO(tplt)) + result = t.ParseText('one\nonetwo') + self.assertListEqual(result, [['one', []], ['one', ['two']]]) + + def testFilldownAlternationWithoutValueGroup(self): + """Filldown memory is not wiped by a non-participating group.""" + + tplt = ( + 'Value Filldown boo (on.)\n' + 'Value hoo (tw.)\n\n' + 'Start\n' + ' ^$boo\n' + ' ^$boo|zz -> Next.Record\n' + ' ^$hoo -> Next.Record\n' + ) + + t = textfsm.TextFSM(io.StringIO(tplt)) + result = t.ParseText('one\nzz\ntw2') + self.assertListEqual( + result, [['one', ''], ['one', 'tw2'], ['one', '']] + ) + def testNestedMatching(self): """List-type values with nested regex capture groups are parsed correctly. diff --git a/textfsm/parser.py b/textfsm/parser.py index 07efb96..07dab49 100755 --- a/textfsm/parser.py +++ b/textfsm/parser.py @@ -960,8 +960,10 @@ def _CheckLine(self, line): for rule in self._cur_state: matched = self._CheckRule(rule, line) if matched: - for value in matched.groupdict(): - self._AssignVar(matched, value) + for name, text in matched.groupdict().items(): + if text is None: + continue # Group not part of the matched branch. + self._AssignVar(matched, name) if self._Operations(rule, line): # Not a Continue so check for state transition. @@ -991,6 +993,8 @@ def _AssignVar(self, matched, value): If a record entry is a list then append, otherwise values are replaced. + Groups that did not participate in the match leave the value unchanged. + Args: matched: (regexp.match) Named group for each matched value. value: (str) The matched value.