From 831c2c57b83b9062cdbff25b4bb7fa07e73e7834 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Luk=C3=A1=C5=A1=20Zachar?= <1548503+lukaszachy@users.noreply.github.com> Date: Fri, 29 Nov 2024 14:57:05 +0100 Subject: [PATCH] Handle missing attribute for merge/minus operation (#254) Operations '~', '-~' and '-' should do nothing if the key is not present. Otherwise they are difficult to use with shared adjust snippets as keys might not always be present. --- fmf/base.py | 13 ++++++++----- tests/unit/test_base.py | 8 ++++---- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/fmf/base.py b/fmf/base.py index 0e7222b..1791109 100644 --- a/fmf/base.py +++ b/fmf/base.py @@ -173,7 +173,7 @@ def _initialize(self, path): def _merge_plus(self, data, key, value, prepend=False): """ Handle extending attributes using the '+' suffix """ - # Nothing to do if key not in parent + # Set the value if key is not present if key not in data: data[key] = value return @@ -222,6 +222,9 @@ def _merge_plus(self, data, key, value, prepend=False): def _merge_regexp(self, data, key, value): """ Handle substitution of current values """ + # Nothing to substitute if the key is not present in parent + if key not in data: + return if isinstance(value, str): value = [value] for pattern, replacement in [utils.split_pattern_replacement(v) for v in value]: @@ -247,6 +250,9 @@ def lazy_any_search(item, patterns): if re.search(p, str(item)): return True return False + # Nothing to remove if the key is not present in parent + if key not in data: + return if isinstance(value, str): value = [value] if isinstance(data[key], list): @@ -267,10 +273,7 @@ def _merge_minus(self, data, key, value): """ Handle reducing attributes using the '-' suffix """ # Cannot reduce attribute if key is not present in parent if key not in data: - data[key] = value - raise utils.MergeError( - "MergeError: Key '{0}' in {1} (not inherited).".format( - key, self.name)) + return # Subtract numbers if type(data[key]) == type(value) in [int, float]: data[key] = data[key] - value diff --git a/tests/unit/test_base.py b/tests/unit/test_base.py index 0e97424..1fadab7 100644 --- a/tests/unit/test_base.py +++ b/tests/unit/test_base.py @@ -196,10 +196,10 @@ def test_merge_minus(self): assert child.data['time'] == 5 assert child.data['vars'] == dict(x=1) assert 'time+' not in child.data - with pytest.raises(utils.MergeError): - child.data["disabled-"] = True - child.inherit() - child.data.pop('disabled-') + # Do not raise MergeError if key is missing + child.data["pkgs-"] = 'foo' + child.inherit() + assert 'pkgs-' not in child.data with pytest.raises(utils.MergeError): child.data["time-"] = "bad" child.inherit()