Skip to content

Commit

Permalink
Handle missing attribute for merge/minus operation
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
lukaszachy committed Sep 3, 2024
1 parent f4fb82e commit 2164073
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
13 changes: 8 additions & 5 deletions fmf/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,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
Expand All @@ -193,6 +193,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]:
Expand All @@ -218,6 +221,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):
Expand All @@ -238,10 +244,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
Expand Down
8 changes: 4 additions & 4 deletions tests/unit/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -170,10 +170,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()
Expand Down

0 comments on commit 2164073

Please sign in to comment.