From 0045d8d03205a0abdd3c543713bb6a8e5f5602a9 Mon Sep 17 00:00:00 2001 From: Brett Smith Date: Tue, 5 Jan 2021 15:07:49 -0500 Subject: [PATCH] fields: Add FormField.add_kid() method. --- conservancy_beancount/pdfforms/fields.py | 6 ++++++ tests/test_pdfforms_fields.py | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/conservancy_beancount/pdfforms/fields.py b/conservancy_beancount/pdfforms/fields.py index 23ebd6e..e8786e4 100644 --- a/conservancy_beancount/pdfforms/fields.py +++ b/conservancy_beancount/pdfforms/fields.py @@ -131,6 +131,12 @@ class FormField: except KeyError: return None + def add_kid(self, kid: 'FormField') -> None: + if kid.parent() is not None: + raise ValueError("given kid field already has a parent") + kid._source['Parent'] = self._source + self._source.setdefault('Kids', []).append(kid._source) + def is_terminal(self) -> bool: return not self._get_value('Kids', None) diff --git a/tests/test_pdfforms_fields.py b/tests/test_pdfforms_fields.py index 8f54120..5ff3475 100644 --- a/tests/test_pdfforms_fields.py +++ b/tests/test_pdfforms_fields.py @@ -368,3 +368,11 @@ def test_recursive_as_mapping(): _, _, expected_name = expected_key.rpartition('.') assert field.name() == expected_name assert next(actual, None) is None + +def test_add_kid(): + parent = fieldsmod.FormField(field_source('parent')) + kid = fieldsmod.FormField(field_source('kid')) + parent.add_kid(kid) + actual, = parent.kids() + assert actual.name() == 'kid' + assert actual.parent().name() == 'parent'