-
Notifications
You must be signed in to change notification settings - Fork 3
feat: Enhance config validation (Resolves #33) #42
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
dyrpsf
wants to merge
2
commits into
draeger-lab:dev
Choose a base branch
from
dyrpsf:feature/issue-33-config-validation
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+133
−2
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,3 +1,4 @@ | ||
| __all__ = ["util", "set_up"] | ||
|
|
||
| from . import util, set_up | ||
| from .config_validator import validate_config, SchemaField, ConfigValidationError | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,130 @@ | ||
| import os | ||
| import logging | ||
| from typing import Any, Dict, List, Optional, Union, Callable | ||
|
dyrpsf marked this conversation as resolved.
Outdated
|
||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class ConfigValidationError(Exception): | ||
| """Custom exception for configuration validation errors.""" | ||
|
|
||
| pass | ||
|
|
||
|
|
||
| class SchemaField: | ||
| """Defines the expected structure, type, and constraints of a config field.""" | ||
|
|
||
| def __init__( | ||
| self, | ||
| expected_type: type | tuple, | ||
| default: Any = None, | ||
| required: bool = False, | ||
| min_val: Optional[Union[int, float]] = None, | ||
| max_val: Optional[Union[int, float]] = None, | ||
| is_path: bool = False, | ||
| path_must_exist: bool = False, | ||
| allowed_values: Optional[List[Any]] = None, | ||
| ): | ||
| self.expected_type = expected_type | ||
| self.default = default | ||
| self.required = required | ||
| self.min_val = min_val | ||
| self.max_val = max_val | ||
| self.is_path = is_path | ||
| self.path_must_exist = path_must_exist | ||
| self.allowed_values = allowed_values | ||
|
|
||
|
|
||
| def validate_config( | ||
| config: Dict[str, Any], schema: Dict[str, Any], path: str = "" | ||
| ) -> Dict[str, Any]: | ||
| """ | ||
| Recursively validates a configuration dictionary against a defined schema. | ||
| Replaces verbose YAML traversal and USER/_USER_ string checks. | ||
| """ | ||
| validated = {} | ||
|
|
||
| for key, rule in schema.items(): | ||
| current_path = f"{path}.{key}" if path else key | ||
| value = config.get(key, rule.default if isinstance(rule, SchemaField) else None) | ||
|
|
||
| # Handle nested dictionaries | ||
| if isinstance(rule, dict): | ||
| if not isinstance(value, dict): | ||
| if value is None: | ||
| value = {} | ||
| else: | ||
| raise ConfigValidationError( | ||
| f"Expected a dictionary at '{current_path}', got {type(value).__name__}." | ||
| ) | ||
| validated[key] = validate_config(value, rule, current_path) | ||
| continue | ||
|
|
||
| if not isinstance(rule, SchemaField): | ||
| raise ConfigValidationError( | ||
| f"Invalid schema definition at '{current_path}'." | ||
| ) | ||
|
|
||
| # 1. Check Required fields (Replaces _USER_ logic) | ||
| if value is None or value == "_USER_": | ||
| if rule.required: | ||
| raise ConfigValidationError( | ||
| f"Missing required configuration parameter: '{current_path}'" | ||
| ) | ||
| elif value == "_USER_": | ||
| logger.error( | ||
| f"Deprecated '_USER_' found at '{current_path}'. Please provide a value or remove it." | ||
| ) | ||
| raise ConfigValidationError( | ||
| f"Missing required parameter: '{current_path}'" | ||
| ) | ||
|
|
||
| # Replaces USER -> None logic with sensible defaults | ||
| if value == "USER": | ||
| logger.warning( | ||
| f"Deprecated 'USER' keyword found at '{current_path}'. Using default: {rule.default}" | ||
| ) | ||
| validated[key] = rule.default | ||
| continue | ||
|
dyrpsf marked this conversation as resolved.
Outdated
|
||
|
|
||
| # Clean up legacy 'USER' keyword | ||
| if value == "USER": | ||
| logger.warning( | ||
| f"Deprecated 'USER' keyword found at '{current_path}'. Using default: {rule.default}" | ||
| ) | ||
| value = rule.default | ||
|
|
||
| # 2. Type Checking | ||
| if value is not None and not isinstance(value, rule.expected_type): | ||
| raise ConfigValidationError( | ||
| f"Type mismatch at '{current_path}': Expected {rule.expected_type}, got {type(value)}." | ||
| ) | ||
|
dyrpsf marked this conversation as resolved.
|
||
|
|
||
| # 3. Numeric Bounds Checking | ||
| if isinstance(value, (int, float)): | ||
| if rule.min_val is not None and value < rule.min_val: | ||
| raise ConfigValidationError( | ||
| f"Value at '{current_path}' ({value}) is below minimum allowed ({rule.min_val})." | ||
| ) | ||
| if rule.max_val is not None and value > rule.max_val: | ||
| raise ConfigValidationError( | ||
| f"Value at '{current_path}' ({value}) is above maximum allowed ({rule.max_val})." | ||
| ) | ||
|
|
||
| # 4. Allowed Values Checking (Strings, etc.) | ||
| if rule.allowed_values is not None and value not in rule.allowed_values: | ||
| raise ConfigValidationError( | ||
| f"Value at '{current_path}' ({value}) must be one of {rule.allowed_values}." | ||
| ) | ||
|
|
||
| # 5. Path Validation | ||
| if rule.is_path and value is not None: | ||
| value = str(value) | ||
| if rule.path_must_exist and not os.path.exists(value): | ||
| raise ConfigValidationError( | ||
| f"Path specified at '{current_path}' does not exist: {value}" | ||
| ) | ||
|
|
||
| validated[key] = value | ||
|
|
||
| return validated | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.