Skip to content

Commit

Permalink
support merged dictionary in Configurable
Browse files Browse the repository at this point in the history
Signed-off-by: Jeffrey Martin <[email protected]>
  • Loading branch information
jmartin-tech committed Jun 18, 2024
1 parent 1fca119 commit f4d77b6
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
5 changes: 5 additions & 0 deletions garak/configurable.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,8 @@ def _apply_config(self, config):
)
):
continue
if isinstance(v, dict): # if value is an existing dictionary merge
v = getattr(self, k) | v
setattr(self, k, v) # This will set attribute to the full dictionary value

def _apply_missing_instance_defaults(self):
Expand All @@ -96,6 +98,9 @@ def _apply_missing_instance_defaults(self):
for k, v in self.DEFAULT_PARAMS.items():
if not hasattr(self, k):
setattr(self, k, v)
elif isinstance(v, dict):
v = v | getattr(self, k)
setattr(self, k, v)

def _validate_env_var(self):
if hasattr(self, "key_env_var"):
Expand Down
19 changes: 18 additions & 1 deletion tests/test_configurable.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,13 @@ class mockConfigurable(Configurable):
# Configurable is coupled to hierarchy of plugin types
__module__ = "garak.generators.mock"

DEFAULT_PARAMS = {"class_var": "from_class"}
DEFAULT_PARAMS = {
"class_var": "from_class",
"class_dict_var": {
"dict_a": "dict_val",
"dict_b": "dict_val",
},
}

def __init__(
self,
Expand Down Expand Up @@ -63,6 +69,17 @@ def test_param_provided(generator_sub_config):
def test_class_vars_propagate_to_instance(generator_sub_config):
m = mockConfigurable(config_root=generator_sub_config)
assert m.class_var == m.DEFAULT_PARAMS["class_var"]
assert m.class_dict_var == m.DEFAULT_PARAMS["class_dict_var"]


# when a default parameter dictionary is provided merge on the resulting object
def test_class_dict_merge_to_instance(generator_sub_config):
config_dict_var = {"dict_a": "test_val", "dict_c": "test_val"}
generator_sub_config.generators["mock"]["class_dict_var"] = config_dict_var
m = mockConfigurable(config_root=generator_sub_config)
assert m.class_dict_var == m.DEFAULT_PARAMS["class_dict_var"] | config_dict_var
assert m.class_dict_var["dict_a"] == config_dict_var["dict_a"]
assert m.class_dict_var["dict_c"] == config_dict_var["dict_c"]


# when a default parameter is provided and not config_root set on the resulting object
Expand Down

0 comments on commit f4d77b6

Please sign in to comment.