Coverage for glotter/errors.py: 100%
34 statements
« prev ^ index » next coverage.py v7.10.7, created at 2026-03-01 21:54 +0000
« prev ^ index » next coverage.py v7.10.7, created at 2026-03-01 21:54 +0000
1from typing import List, NoReturn, Optional
3from pydantic import ValidationError
4from pydantic_core import InitErrorDetails, PydanticCustomError
7def get_error_details(msg: str, loc: tuple, input) -> InitErrorDetails:
8 return InitErrorDetails(
9 type=PydanticCustomError("value_error", msg),
10 loc=loc,
11 input=input,
12 )
15def raise_simple_validation_error(cls, msg, input, loc: Optional[tuple] = None) -> NoReturn:
16 raise ValidationError.from_exception_data(
17 title=cls.__name__,
18 line_errors=[get_error_details(msg, loc or (), input)],
19 )
22def raise_validation_errors(cls, errors: List[InitErrorDetails]) -> NoReturn:
23 raise ValidationError.from_exception_data(title=cls.__name__, line_errors=errors)
26def validate_str_list(
27 cls, values, item_loc: Optional[tuple] = None, raise_exc: bool = True
28) -> List[InitErrorDetails]:
29 loc = item_loc or ()
30 errors = []
31 if not isinstance(values, list):
32 errors += [get_error_details("Input should be a valid list", loc, values)]
33 else:
34 errors += [
35 get_error_details("Input should be a valid string", loc + (index,), value)
36 for index, value in enumerate(values)
37 if not isinstance(value, str)
38 ]
40 if errors and raise_exc:
41 raise_validation_errors(cls, errors)
43 return errors
46def validate_str_dict(
47 cls, values, item_loc: Optional[tuple] = None, raise_exc: bool = True
48) -> List[InitErrorDetails]:
49 loc = item_loc or ()
50 errors = []
51 if not isinstance(values, dict):
52 errors += [get_error_details("Input should be a valid dictionary", loc, values)]
53 else:
54 errors += sum(
55 (
56 _get_str_dict_error_details(loc + (key,), key, value)
57 for key, value in values.items()
58 if not isinstance(key, str) or not isinstance(value, str)
59 ),
60 [],
61 )
63 if errors and raise_exc:
64 raise_validation_errors(cls, errors)
66 return errors
69def _get_str_dict_error_details(loc, key, value) -> List[InitErrorDetails]:
70 errors = []
71 if not isinstance(key, str):
72 errors += [get_error_details("Key should be a valid string", loc, key)]
74 if not isinstance(value, str):
75 errors += [get_error_details("Value should be a valid string", loc, value)]
77 return errors