assettrack/functions/validate_config.py

48 lines
2.2 KiB
Python

from typing import List
from definitions.attribute import Attribute
#VALID_OPERATORS = {"lt", "gt", "le", "ge", "eq", "ne"} # <, >, <=, >=, ==, !=
VALID_COMPARISONS = {
"number": {"lt", "gt", "le", "ge", "eq", "ne"}, # <, >, <=, >=, ==, !=
"text": {"lt", "st", "eq", "ne"}, # longer than, shorter than, eq, or not eq, to the ref attrib
"date": {"lt", "gt", "le", "ge", "eq", "ne"}, # <, >, <=, >=, ==, !=
"select": {"eq", "ne"} # eq, or not eq, to the ref attrib
}
def validate_config(item_attributes: List[Attribute]) -> str:
"""
Validate the configuration file to ensure all attributes are properly defined.
Returns "Ok" if everything is valid, otherwise returns an error message.
"""
if not item_attributes:
return "Configuration must contain at least one attribute."
attrib_names = [attrib.attrib_name for attrib in item_attributes]
attrib_name_set = set(attrib_names)
# Check for duplicate attribute names
if len(attrib_names) != len(attrib_name_set):
return "Duplicate attribute names are not allowed."
# Validate each attribute
for attrib in item_attributes:
error = attrib.validate()
if error:
return error
# Validate comparison (if applicable)
if attrib.compareto:
if not isinstance(attrib.compareto, list) or not all(
isinstance(pair, tuple) and len(pair) == 2 for pair in attrib.compareto
):
return f"Invalid comparison format for attribute '{attrib.attrib_name}'. Expected a list of tuples."
for cmp, ref_attr in attrib.compareto:
if cmp not in VALID_COMPARISONS[attrib.html_input_type]:
return f"Invalid comparison '{cmp}' for attribute '{attrib.attrib_name}'. Allowed operators are: {VALID_COMPARISONS[attrib.html_input_type]}"
if ref_attr not in attrib_name_set:
return f"Invalid reference attribute '{ref_attr}' for comparison in attribute '{attrib.attrib_name}'."
if ref_attr.html_input_type != attrib.html_input_type:
return f"Invalid comparison of '{attrib}' & '{ref_attr}' - must be of the same type, {attrib.html_input_type}."
return "Ok"