]> git.ipfire.org Git - thirdparty/knot-resolver.git/commitdiff
manager: parser validator: changed primitive type coercion
authorVasek Sraier <git@vakabus.cz>
Thu, 15 Apr 2021 11:36:07 +0000 (13:36 +0200)
committerAleš Mrázek <ales.mrazek@nic.cz>
Fri, 8 Apr 2022 14:17:52 +0000 (16:17 +0200)
int, float -> str    ...   allowed and will happen
str -> int, float    ...   disallowed
float -> int         ...   allowed and will happen
int -> float         ...   allowed and will happen

manager/knot_resolver_manager/utils/dataclasses_parservalidator.py

index 1732f077a539af077f4253a266460e13217009ce..3f565e51a72c5f2fd29a941ed038f290688c8e33 100644 (file)
@@ -49,12 +49,20 @@ def _from_dictlike_obj(cls: Any, obj: Any, default: Any, use_default: bool) -> A
     elif obj is None:
         raise ValidationException(f"Unexpected None value for type {cls}")
 
-    # primitive types
-    if cls in (int, float, str):
-        try:
+    # floats and ints
+    elif cls in (int, float):
+        # special case checking, that we won't cast a string or any other object into a number
+        if isinstance(obj, (int, float)):
             return cls(obj)
-        except ValueError as e:
-            raise ValidationException(f"Failed to parse primitive type {cls}, value {obj}", e)
+        else:
+            raise ValidationException(f"Expected {cls}, found {type(obj)}")
+    
+    # str
+    elif cls == str:
+        # we are willing to cast any primitive value to string, but no compound values are allowed
+        if not isinstance(obj, (str, float, int)):
+            raise ValidationException(f"Expected str (or number that would be cast to string), but found type {type(obj)}")
+        return str(obj)
 
     # Literal[T]
     elif is_literal(cls):