Skip to content

Commit

Permalink
[pre-commit.ci] auto fixes from pre-commit.com hooks
Browse files Browse the repository at this point in the history
for more information, see https://pre-commit.ci
  • Loading branch information
pre-commit-ci[bot] committed Oct 2, 2024
1 parent 425ea51 commit 1870359
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 12 deletions.
3 changes: 2 additions & 1 deletion dicfg/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ class ConfigDict(ConfigValue, UserDict):
data (dict): value of the config
"""

def _init(self, data: dict):
for key in list(data):
_key, merger = _get_merger(key, data[key])
Expand Down Expand Up @@ -101,7 +102,7 @@ def validate(self):
yield from super().validate()
for value in self.data:
yield from value.validate()

def cast(self):
"""Cast wrapped value to builtin python value"""
return [value.cast() for value in self.data]
Expand Down
4 changes: 2 additions & 2 deletions dicfg/reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ def read(
user_presets = read_user_config.pop("presets", ())
user_configs.append(read_user_config)
user_presets_configs.extend(self._read_presets(user_presets))

configs = (
self_config,
*tuple(user_presets_configs),
Expand All @@ -126,7 +126,7 @@ def read(

if errors := list(merged_configs.validate()):
raise ValidationErrors(errors)

return merged_configs.cast()

def _set_search_paths(self, user_config_search_paths, search_paths):
Expand Down
25 changes: 17 additions & 8 deletions dicfg/validators.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,18 @@

from dicfg.factory import WHITE_LIST_FACTORY_KEYS, OBJECT_KEY


@dataclass(frozen=True)
class ValidationError:
message: str

class UnsupportedValidatorError(ValueError):
...

class UnsupportedValidatorError(ValueError): ...


class ValidationErrors(Exception):
"""Exception raised when validation errors occur"""

def __init__(self, errors: list[ValidationError]):
formatted_errors = "\n".join([err.message for err in errors])
super().__init__(f"\n{formatted_errors}")
Expand Down Expand Up @@ -66,7 +69,7 @@ class ConfigPositiveNumberValidator(ConfigValidator):
def validate(self, value):
if not (isinstance(value, Number) and value >= 0):
return ValidationError("Value must be a positive number.")


class ConfigPositiveNumberListValidator(ConfigValidator):
"""Validator that checks if a value is a positive number"""
Expand All @@ -76,8 +79,8 @@ class ConfigPositiveNumberListValidator(ConfigValidator):
def validate(self, value):
if not (isinstance(value, list) and all([v.cast() >= 0 for v in value])):
return ValidationError("Value must be a list with only positive numbers.")


class ConfigObjectValidator(ConfigValidator):
"""Validator that checks if a value is a valid object configuration"""

Expand All @@ -88,7 +91,9 @@ def validate(self, value: dict) -> ValidationError:
return ValidationError("Value must be a dictionary.")

if OBJECT_KEY not in value:
return ValidationError(f"The key {OBJECT_KEY} must be present in the configuration.")
return ValidationError(
f"The key {OBJECT_KEY} must be present in the configuration."
)

object_path = value[OBJECT_KEY].cast()
try:
Expand All @@ -98,7 +103,9 @@ def validate(self, value: dict) -> ValidationError:
if not callable(obj):
return ValidationError(f"'{object_path}' is not callable.")
except (ImportError, AttributeError, ValueError) as e:
return ValidationError(f"Failed to import or access callable for {OBJECT_KEY}: {str(e)}")
return ValidationError(
f"Failed to import or access callable for {OBJECT_KEY}: {str(e)}"
)

sig = inspect.signature(obj)

Expand All @@ -108,4 +115,6 @@ def validate(self, value: dict) -> ValidationError:

for key in remaining_keys:
if key not in sig.parameters:
return ValidationError(f"'{key}' is not a valid argument for '{object_path}'.")
return ValidationError(
f"'{key}' is not a valid argument for '{object_path}'."
)
2 changes: 1 addition & 1 deletion tests/validators_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ def test_object_no_callable_error():
with raises(ValidationErrors):
config_reader.read(user_config)


def test_invalid_validator_error():
user_config = {"validators": {"testing@validate(error)@replace(true)": []}}
config_reader = ConfigReader(
Expand All @@ -108,4 +109,3 @@ def test_invalid_validator_error():
)
with raises(UnsupportedValidatorError):
config_reader.read(user_config)

0 comments on commit 1870359

Please sign in to comment.