]> git.ipfire.org Git - thirdparty/knot-resolver.git/commitdiff
manager: utils: modeling: naming improvements
authorAleš Mrázek <ales.mrazek@nic.cz>
Wed, 13 Jul 2022 08:39:39 +0000 (10:39 +0200)
committerAleš Mrázek <ales.mrazek@nic.cz>
Wed, 13 Jul 2022 08:39:39 +0000 (10:39 +0200)
28 files changed:
manager/knot_resolver_manager/datamodel/cache_schema.py
manager/knot_resolver_manager/datamodel/config_schema.py
manager/knot_resolver_manager/datamodel/dns64_schema.py
manager/knot_resolver_manager/datamodel/dnssec_schema.py
manager/knot_resolver_manager/datamodel/forward_zone_schema.py
manager/knot_resolver_manager/datamodel/logging_schema.py
manager/knot_resolver_manager/datamodel/lua_schema.py
manager/knot_resolver_manager/datamodel/management_schema.py
manager/knot_resolver_manager/datamodel/monitoring_schema.py
manager/knot_resolver_manager/datamodel/network_schema.py
manager/knot_resolver_manager/datamodel/options_schema.py
manager/knot_resolver_manager/datamodel/policy_schema.py
manager/knot_resolver_manager/datamodel/rpz_schema.py
manager/knot_resolver_manager/datamodel/slice_schema.py
manager/knot_resolver_manager/datamodel/static_hints_schema.py
manager/knot_resolver_manager/datamodel/stub_zone_schema.py
manager/knot_resolver_manager/datamodel/types/base_types.py
manager/knot_resolver_manager/datamodel/types/types.py
manager/knot_resolver_manager/datamodel/view_schema.py
manager/knot_resolver_manager/datamodel/webmgmt_schema.py
manager/knot_resolver_manager/utils/modeling/README.md
manager/knot_resolver_manager/utils/modeling/__init__.py
manager/knot_resolver_manager/utils/modeling/base_custom_type.py [moved from manager/knot_resolver_manager/utils/modeling/custom_value_type.py with 75% similarity]
manager/knot_resolver_manager/utils/modeling/base_schema.py [moved from manager/knot_resolver_manager/utils/modeling/schema_node.py with 90% similarity]
manager/knot_resolver_manager/utils/modeling/parsing.py [moved from manager/knot_resolver_manager/utils/modeling/parsed_tree.py with 100% similarity]
manager/tests/unit/datamodel/types/test_custom_types.py
manager/tests/unit/utils/test_modeling.py
manager/tests/unit/utils/test_types.py

index 6b2a73419b3be91e46e54ed3d5c9bfed91cbab59..831826274ab070f8b574fc56579245b4cd44594d 100644 (file)
@@ -1,10 +1,10 @@
 from typing import List, Optional
 
 from knot_resolver_manager.datamodel.types import CheckedPath, DomainName, SizeUnit, TimeUnit
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class PrefillSchema(SchemaNode):
+class PrefillSchema(BaseSchema):
     """
     Prefill the cache periodically by importing zone data obtained over HTTP.
 
@@ -25,7 +25,7 @@ class PrefillSchema(SchemaNode):
             raise ValueError("cache prefilling is not yet supported for non-root zones")
 
 
-class CacheSchema(SchemaNode):
+class CacheSchema(BaseSchema):
     """
     DNS resolver cache configuration.
 
index 54462884cfecb68f81cdc9e374263a6ad1dfcc3d..26194b04924f6b140c1d3776b59d3d7939083cb1 100644 (file)
@@ -26,7 +26,7 @@ from knot_resolver_manager.datamodel.stub_zone_schema import StubZoneSchema
 from knot_resolver_manager.datamodel.types.types import IntPositive, UncheckedPath
 from knot_resolver_manager.datamodel.view_schema import ViewSchema
 from knot_resolver_manager.datamodel.webmgmt_schema import WebmgmtSchema
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 logger = logging.getLogger(__name__)
 
@@ -71,8 +71,8 @@ def _cpu_count() -> Optional[int]:
         return cpus
 
 
-class KresConfig(SchemaNode):
-    class Raw(SchemaNode):
+class KresConfig(BaseSchema):
+    class Raw(BaseSchema):
         """
         Knot Resolver declarative configuration.
 
index b6cdb31536104c78d98be91acdb957d663ff68cf..0561f56e342456a2babc1c4fc01a17184b0426b1 100644 (file)
@@ -1,8 +1,8 @@
 from knot_resolver_manager.datamodel.types import IPv6Network96
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class Dns64Schema(SchemaNode):
+class Dns64Schema(BaseSchema):
     """
     DNS64 (RFC 6147) configuration.
 
index ab9e325b06adfce8bcc735325e413653a230e85d..f81374d563118fa0b6c2ddcd6f33ae96b7d99d28 100644 (file)
@@ -1,10 +1,10 @@
 from typing import List, Optional
 
 from knot_resolver_manager.datamodel.types import IntNonNegative, TimeUnit
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class TrustAnchorFileSchema(SchemaNode):
+class TrustAnchorFileSchema(BaseSchema):
     """
     Trust-anchor zonefile configuration.
 
@@ -18,7 +18,7 @@ class TrustAnchorFileSchema(SchemaNode):
     read_only: bool = False
 
 
-class DnssecSchema(SchemaNode):
+class DnssecSchema(BaseSchema):
     """
     DNSSEC configuration.
 
index 04acef15497692b49cc7090e230e58b289861b59..b52c3ee96cac3502346b2d23cba6b3f95beef69c 100644 (file)
@@ -2,10 +2,10 @@ from typing import List, Optional, Union
 
 from knot_resolver_manager.datamodel.policy_schema import ForwardServerSchema
 from knot_resolver_manager.datamodel.types import DomainName, IPAddressOptionalPort, PolicyFlagEnum
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class ForwardZoneSchema(SchemaNode):
+class ForwardZoneSchema(BaseSchema):
     """
     Configuration of Forward Zone.
 
index 22d390c484c9b6931c9a6b83b0a58147010915dd..73ffa46fa20cecbfb25b03c34ea840ba4726a843 100644 (file)
@@ -3,7 +3,7 @@ from typing import List, Optional, Set, Union
 from typing_extensions import Literal, TypeAlias
 
 from knot_resolver_manager.datamodel.types import CheckedPath, TimeUnit
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 LogLevelEnum = Literal["crit", "err", "warning", "notice", "info", "debug"]
 LogTargetEnum = Literal["syslog", "stderr", "stdout"]
@@ -57,7 +57,7 @@ LogGroupsEnum: TypeAlias = Literal[
 ]
 
 
-class DnstapSchema(SchemaNode):
+class DnstapSchema(BaseSchema):
     """
     Logging DNS queries and responses to a unix socket.
 
@@ -74,7 +74,7 @@ class DnstapSchema(SchemaNode):
     log_tcp_rtt: bool = True
 
 
-class DebuggingSchema(SchemaNode):
+class DebuggingSchema(BaseSchema):
     """
     Advanced debugging parameters for kresd (Knot Resolver daemon).
 
@@ -87,7 +87,7 @@ class DebuggingSchema(SchemaNode):
     assertion_fork: TimeUnit = TimeUnit("5m")
 
 
-class LoggingSchema(SchemaNode):
+class LoggingSchema(BaseSchema):
     """
     Logging and debugging configuration.
 
index 7dfb0d62e81326af590f69a33c1722f32bb4f591..174c8540ac0f9a01f28bfd5f70ed0e15175bfc31 100644 (file)
@@ -1,9 +1,9 @@
 from typing import Optional
 
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class LuaSchema(SchemaNode):
+class LuaSchema(BaseSchema):
     """
     Custom Lua configuration.
 
index 75b8613f02b1caf4e586724dfb4fb8850819348a..e58f1a728ab1edae543a5a65bf4f28c52f203da5 100644 (file)
@@ -1,10 +1,10 @@
 from typing import Optional
 
 from knot_resolver_manager.datamodel.types import CheckedPath, IPAddressPort
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class ManagementSchema(SchemaNode):
+class ManagementSchema(BaseSchema):
     """
     Configuration of management HTTP API.
 
index adc40640742e9f5937ac257a0178d69fc6ce260a..d2f259ef8281c075597c11d18fc94a2210b6a0b4 100644 (file)
@@ -3,10 +3,10 @@ from typing import Union
 from typing_extensions import Literal
 
 from knot_resolver_manager.datamodel.types import DomainName, IPAddress, PortNumber, TimeUnit
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class GraphiteSchema(SchemaNode):
+class GraphiteSchema(BaseSchema):
     host: Union[IPAddress, DomainName]
     port: PortNumber = PortNumber(2003)
     prefix: str = ""
@@ -14,7 +14,7 @@ class GraphiteSchema(SchemaNode):
     tcp: bool = False
 
 
-class MonitoringSchema(SchemaNode):
+class MonitoringSchema(BaseSchema):
     """
     ---
     enabled: configures, whether statistics module will be loaded into resolver
index e0760dcf55e97ace1c576d56e694f6d283a35553..3bdad9a50e36bd7e33cc15fe86a9944204d41c06 100644 (file)
@@ -14,12 +14,12 @@ from knot_resolver_manager.datamodel.types import (
     PortNumber,
     SizeUnit,
 )
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 KindEnum = Literal["dns", "xdp", "dot", "doh-legacy", "doh2"]
 
 
-class EdnsBufferSizeSchema(SchemaNode):
+class EdnsBufferSizeSchema(BaseSchema):
     """
     EDNS payload size advertised in DNS packets.
 
@@ -32,7 +32,7 @@ class EdnsBufferSizeSchema(SchemaNode):
     downstream: SizeUnit = SizeUnit("1232B")
 
 
-class AddressRenumberingSchema(SchemaNode):
+class AddressRenumberingSchema(BaseSchema):
     """
     Renumbers addresses in answers to different address space.
 
@@ -45,7 +45,7 @@ class AddressRenumberingSchema(SchemaNode):
     destination: IPAddress
 
 
-class TLSSchema(SchemaNode):
+class TLSSchema(BaseSchema):
     """
     TLS configuration, also affects DNS over TLS and DNS over HTTPS.
 
@@ -70,8 +70,8 @@ class TLSSchema(SchemaNode):
             raise ValueError("'sticket_secret' and 'sticket_secret_file' are both defined, only one can be used")
 
 
-class ListenSchema(SchemaNode):
-    class Raw(SchemaNode):
+class ListenSchema(BaseSchema):
+    class Raw(BaseSchema):
         """
         Configuration of listening interface.
 
@@ -134,7 +134,7 @@ class ListenSchema(SchemaNode):
             )
 
 
-class ProxyProtocolSchema(SchemaNode):
+class ProxyProtocolSchema(BaseSchema):
     """
     PROXYv2 protocol configuration.
 
@@ -145,7 +145,7 @@ class ProxyProtocolSchema(SchemaNode):
     allow: List[Union[IPAddress, IPNetwork]]
 
 
-class NetworkSchema(SchemaNode):
+class NetworkSchema(BaseSchema):
     """
     Network connections and protocols configuration.
 
index a407c27ce087a32101f1d804dbecfaa828f2f851..1ec5072d3dfcefe09dadf5d3df5fa6563abbeaa2 100644 (file)
@@ -3,12 +3,12 @@ from typing import Any, Union
 from typing_extensions import Literal
 
 from knot_resolver_manager.datamodel.types import IntNonNegative, TimeUnit
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 GlueCheckingEnum = Literal["normal", "strict", "permissive"]
 
 
-class PredictionSchema(SchemaNode):
+class PredictionSchema(BaseSchema):
     """
     Helps keep the cache hot by prefetching expiring records and learning usage patterns and repetitive queries.
 
@@ -21,8 +21,8 @@ class PredictionSchema(SchemaNode):
     period: IntNonNegative = IntNonNegative(24)
 
 
-class OptionsSchema(SchemaNode):
-    class Raw(SchemaNode):
+class OptionsSchema(BaseSchema):
+    class Raw(BaseSchema):
         """
         Fine-tuning global parameters of DNS resolver operation.
 
index d17d462af3c2374969d12e24c146fd987a8f6a35..f081879b024eb6685aeddb0a1afdb903f3419451 100644 (file)
@@ -10,10 +10,10 @@ from knot_resolver_manager.datamodel.types import (
     PolicyFlagEnum,
     TimeUnit,
 )
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class FilterSchema(SchemaNode):
+class FilterSchema(BaseSchema):
     """
     Query filtering configuration.
 
@@ -28,7 +28,7 @@ class FilterSchema(SchemaNode):
     qtype: Optional[DNSRecordTypeEnum] = None
 
 
-class AnswerSchema(SchemaNode):
+class AnswerSchema(BaseSchema):
     """
     Configuration of custom resource record for DNS answer.
 
@@ -45,7 +45,7 @@ class AnswerSchema(SchemaNode):
     nodata: bool = False
 
 
-class ForwardServerSchema(SchemaNode):
+class ForwardServerSchema(BaseSchema):
     """
     Configuration of Forward server.
 
@@ -92,7 +92,7 @@ def _validate_policy_action(policy_action: Union["ActionSchema", "PolicySchema"]
                 )
 
 
-class ActionSchema(SchemaNode):
+class ActionSchema(BaseSchema):
     """
     Configuration of policy action.
 
@@ -114,7 +114,7 @@ class ActionSchema(SchemaNode):
         _validate_policy_action(self)
 
 
-class PolicySchema(SchemaNode):
+class PolicySchema(BaseSchema):
     """
     Configuration of policy rule.
 
index 078a4aad2030f7555dc83730baebe757a9e1c484..a0032b70b80bd5520b7a2fc2080e16e051fe9df8 100644 (file)
@@ -1,10 +1,10 @@
 from typing import List, Optional
 
 from knot_resolver_manager.datamodel.types import CheckedPath, PolicyActionEnum, PolicyFlagEnum
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class RPZSchema(SchemaNode):
+class RPZSchema(BaseSchema):
     """
     Configuration or Response Policy Zone (RPZ).
 
index 8606da08231ce56f16819e3f567e31415035cf71..119d9a16b9d37722d39aadb0ca96c60b7dff90fd 100644 (file)
@@ -3,10 +3,10 @@ from typing import List, Optional
 from typing_extensions import Literal
 
 from knot_resolver_manager.datamodel.policy_schema import ActionSchema
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class SliceSchema(SchemaNode):
+class SliceSchema(BaseSchema):
     """
     Split the entire DNS namespace into distinct slices.
 
index 33144c083e9eda7533b601a5b17464f20cc34e5d..1a45d9a1fdf26111a2405c4623cc5df994f95a93 100644 (file)
@@ -1,10 +1,10 @@
 from typing import Dict, List, Optional
 
 from knot_resolver_manager.datamodel.types import CheckedPath, DomainName, IPAddress, TimeUnit
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class StaticHintsSchema(SchemaNode):
+class StaticHintsSchema(BaseSchema):
     """
     Static hints for forward records (A/AAAA) and reverse records (PTR)
 
index f3be8f8b642af539796164252d1bda6de585f42b..1ff980562c5832566196fe88c30f4a1c8e5e3a66 100644 (file)
@@ -1,10 +1,10 @@
 from typing import List, Optional, Union
 
 from knot_resolver_manager.datamodel.types import DomainName, IPAddressOptionalPort, PolicyFlagEnum
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class StubServerSchema(SchemaNode):
+class StubServerSchema(BaseSchema):
     """
     Configuration of Stub server.
 
@@ -15,7 +15,7 @@ class StubServerSchema(SchemaNode):
     address: IPAddressOptionalPort
 
 
-class StubZoneSchema(SchemaNode):
+class StubZoneSchema(BaseSchema):
     """
     Configuration of Stub Zone.
 
index 1ceab0a87610749dc66743878a9cefcc8bf6d466..274fd2eb37f6c4942dd23b7f48b0df10decca6d6 100644 (file)
@@ -1,11 +1,11 @@
 import re
 from typing import Any, Dict, Pattern, Type
 
-from knot_resolver_manager.utils.modeling import CustomValueType
+from knot_resolver_manager.utils.modeling import BaseCustomType
 from knot_resolver_manager.utils.modeling.exceptions import DataValidationError
 
 
-class IntBase(CustomValueType):
+class IntBase(BaseCustomType):
     """
     Base class to work with integer value.
     """
@@ -29,7 +29,7 @@ class IntBase(CustomValueType):
         return {"type": "integer"}
 
 
-class StrBase(CustomValueType):
+class StrBase(BaseCustomType):
     """
     Base class to work with string value.
     """
index c88aa026a71e7de6de9aefa5648b683f3fc00c0d..bb6e635b138d7ea4f219aabc94be59330b6911a9 100644 (file)
@@ -4,7 +4,7 @@ from pathlib import Path
 from typing import Any, Dict, Optional, Type, Union
 
 from knot_resolver_manager.datamodel.types.base_types import IntRangeBase, PatternBase, StrBase, UnitBase
-from knot_resolver_manager.utils.modeling import CustomValueType
+from knot_resolver_manager.utils.modeling import BaseCustomType
 from knot_resolver_manager.utils.modeling.exceptions import DataValidationError
 
 
@@ -240,7 +240,7 @@ class IPAddressOptionalPort(StrBase):
             )
 
 
-class IPv4Address(CustomValueType):
+class IPv4Address(BaseCustomType):
     _value: ipaddress.IPv4Address
 
     def __init__(self, source_value: Any, object_path: str = "/") -> None:
@@ -282,7 +282,7 @@ class IPv4Address(CustomValueType):
         }
 
 
-class IPv6Address(CustomValueType):
+class IPv6Address(BaseCustomType):
     _value: ipaddress.IPv6Address
 
     def __init__(self, source_value: Any, object_path: str = "/") -> None:
@@ -327,7 +327,7 @@ class IPv6Address(CustomValueType):
 IPAddress = Union[IPv4Address, IPv6Address]
 
 
-class IPNetwork(CustomValueType):
+class IPNetwork(BaseCustomType):
     _value: Union[ipaddress.IPv4Network, ipaddress.IPv6Network]
 
     def __init__(self, source_value: Any, object_path: str = "/") -> None:
@@ -363,7 +363,7 @@ class IPNetwork(CustomValueType):
         }
 
 
-class IPv6Network96(CustomValueType):
+class IPv6Network96(BaseCustomType):
     _value: ipaddress.IPv6Network
 
     def __init__(self, source_value: Any, object_path: str = "/") -> None:
@@ -415,7 +415,7 @@ class IPv6Network96(CustomValueType):
         return {"type": "string"}
 
 
-class UncheckedPath(CustomValueType):
+class UncheckedPath(BaseCustomType):
     """
     Wrapper around pathlib.Path object. Can represent pretty much any Path. No checks are
     performed on the value. The value is taken as is.
index caac0940e07627ba49f18d206e3b7d6261c62457..1e231c2112851d065400cee01c48acf1b116124f 100644 (file)
@@ -1,10 +1,10 @@
 from typing import List, Optional
 
 from knot_resolver_manager.datamodel.types import IPNetwork, PolicyFlagEnum
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class ViewSchema(SchemaNode):
+class ViewSchema(BaseSchema):
     """
     Configuration parameters that allow you to create personalized policy rules and other.
 
index b745f95726d87e0043dca45b9d7b4ef8314cc7b5..c99ddaa0610addf40fe56fc01abfc0b9df54e9a1 100644 (file)
@@ -1,10 +1,10 @@
 from typing import Optional
 
 from knot_resolver_manager.datamodel.types import CheckedPath, InterfacePort
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 
 
-class WebmgmtSchema(SchemaNode):
+class WebmgmtSchema(BaseSchema):
     """
     Configuration of legacy web management endpoint.
 
index db41078cc4a36c6c6bad1cb3a22563500e1a5c52..62eed4546f53613f320d5de36ea8784f16f59765 100644 (file)
@@ -5,12 +5,12 @@ The utilities also take care of parsing, validating and creating JSON schemas an
 
 ## Creating schema
 
-Schema is created using `SchemaNode` class. Schema structure is specified using annotations.
+Schema is created using `BaseSchema` class. Schema structure is specified using annotations.
 
 ```python
-from .modeling import SchemaNode
+from .modeling import BaseSchema
 
-class SimpleSchema(SchemaNode):
+class SimpleSchema(BaseSchema):
     integer: int = 5    # a default value can be specified
     string: str
     boolean: bool
@@ -21,7 +21,7 @@ Words in multi-word names are separated by underscore `_` (e.g. `simple_schema`)
 ```python
 from typing import Dict, List, Optional, Union
 
-class ComplexSchema(SchemaNode):
+class ComplexSchema(BaseSchema):
     optional: Optional[str]     # this field is optional
     union: Union[int, str]      # integer and string are both valid
     list: List[int]             # list of integers
@@ -36,7 +36,7 @@ If a some additional validation needs to be done, there is `_validate()` method
 `ValueError` exception should be raised in case of validation error.
 
 ```python
-class FieldsSchema(SchemaNode):
+class FieldsSchema(BaseSchema):
     field1: int
     field2: int
 
@@ -53,8 +53,8 @@ Transformation method must be named based on field (`value` in this example) wit
 In this example, the `Layer2Schema` is structure for input data and `Layer1Schema` is for result data.
 
 ```python
-class Layer1Schema(SchemaNode):
-    class Layer2Schema(SchemaNode):
+class Layer1Schema(BaseSchema):
+    class Layer2Schema(BaseSchema):
         value: Union[str, int]
 
     _LAYER = Layer2Schema
@@ -72,7 +72,7 @@ class Layer1Schema(SchemaNode):
 Created schema can be documented using simple docstring. Json schema is created by calling `json_schema()` method on schema class. JSON schema includes description from docstring, defaults, etc.
 
 ```python
-SimpleSchema(SchemaNode):
+SimpleSchema(BaseSchema):
     """
     This is description for SimpleSchema itself.
 
@@ -92,14 +92,14 @@ json_schema = SimpleSchema.json_schema()
 
 ## Creating custom type
 
-Custom types can be made by extending `CustomValueType` class which is integrated to parsing and validating process.
+Custom types can be made by extending `BaseCustomType` class which is integrated to parsing and validating process.
 Use `DataValidationError` to rase exception during validation. `object_path` is used to track node in more complex/nested schemas and create useful logging message.
 
 ```python
-from .modeling import CustomValueType
+from .modeling import BaseCustomType
 from .modeling.exceptions import DataValidationError
 
-class IntNonNegative(CustomValueType):
+class IntNonNegative(BaseCustomType):
     def __init__(self, source_value: Any, object_path: str = "/") -> None:
         super().__init__(source_value)
         if isinstance(source_value, int) and not isinstance(source_value, bool):
index cbe017830c6b80c100b9dc4ad22198f11ec41e12..bf3b322f7b99c08facb3685b55a5cd5b9f3bf579 100644 (file)
@@ -1,10 +1,10 @@
-from .custom_value_type import CustomValueType
-from .parsed_tree import ParsedTree, parse, parse_json, parse_yaml
-from .schema_node import SchemaNode
+from .base_custom_type import BaseCustomType
+from .base_schema import BaseSchema
+from .parsing import ParsedTree, parse, parse_json, parse_yaml
 
 __all__ = [
-    "CustomValueType",
-    "SchemaNode",
+    "BaseCustomType",
+    "BaseSchema",
     "ParsedTree",
     "parse",
     "parse_yaml",
similarity index 75%
rename from manager/knot_resolver_manager/utils/modeling/custom_value_type.py
rename to manager/knot_resolver_manager/utils/modeling/base_custom_type.py
index 4b0024ce7eb98fc5c7f886840a1ec1d6ebf57a9f..1da6fe812afa2dc7e287fe7b46a15cde38176c6b 100644 (file)
@@ -1,7 +1,7 @@
 from typing import Any, Dict, Type
 
 
-class CustomValueType:
+class BaseCustomType:
     """
     Subclasses of this class can be used as type annotations in 'DataParser'. When a value
     is being parsed from a serialized format (e.g. JSON/YAML), an object will be created by
@@ -11,9 +11,9 @@ class CustomValueType:
     Example:
     ```
     class A(DataParser):
-        field: MyCustomValueType
+        field: MyBaseCustomType
 
-    A.from_json('{"field": "value"}') == A(field=MyCustomValueType("value"))
+    A.from_json('{"field": "value"}') == A(field=MyBaseCustomType("value"))
     ```
 
     There is no validation done on the wrapped value. The only condition is that
@@ -25,10 +25,10 @@ class CustomValueType:
         pass
 
     def __int__(self) -> int:
-        raise NotImplementedError("CustomValueType return 'int()' value is not implemented.")
+        raise NotImplementedError("BaseCustomType return 'int()' value is not implemented.")
 
     def __str__(self) -> str:
-        raise NotImplementedError("CustomValueType return 'str()' value is not implemented.")
+        raise NotImplementedError("BaseCustomType return 'str()' value is not implemented.")
 
     def serialize(self) -> Any:
         """
@@ -40,5 +40,5 @@ class CustomValueType:
         raise NotImplementedError(f"{type(self).__name__}'s' 'to_dict()' not implemented.")
 
     @classmethod
-    def json_schema(cls: Type["CustomValueType"]) -> Dict[Any, Any]:
+    def json_schema(cls: Type["BaseCustomType"]) -> Dict[Any, Any]:
         raise NotImplementedError()
similarity index 90%
rename from manager/knot_resolver_manager/utils/modeling/schema_node.py
rename to manager/knot_resolver_manager/utils/modeling/base_schema.py
index 0ee00d278266137241cdaa5b2b10f6fff591bd20..09227e1e434386ee2dd9bf60d7bca2d1d26f7645 100644 (file)
@@ -6,9 +6,9 @@ import yaml
 
 from knot_resolver_manager.utils.functional import all_matches
 
-from .custom_value_type import CustomValueType
+from .base_custom_type import BaseCustomType
 from .exceptions import AggregateDataValidationError, DataDescriptionError, DataValidationError
-from .parsed_tree import ParsedTree
+from .parsing import ParsedTree
 from .types import (
     NoneType,
     get_generic_type_argument,
@@ -52,8 +52,8 @@ class Serializable:
             or is_dict(typ)
             or is_list(typ)
             or (inspect.isclass(typ) and issubclass(typ, Serializable))
-            or (inspect.isclass(typ) and issubclass(typ, CustomValueType))
-            or (inspect.isclass(typ) and issubclass(typ, SchemaNode))
+            or (inspect.isclass(typ) and issubclass(typ, BaseCustomType))
+            or (inspect.isclass(typ) and issubclass(typ, BaseSchema))
             or (is_optional(typ) and Serializable.is_serializable(get_optional_inner_type(typ)))
             or (is_union(typ) and all_matches(Serializable.is_serializable, get_generic_type_arguments(typ)))
         )
@@ -63,7 +63,7 @@ class Serializable:
         if isinstance(obj, Serializable):
             return obj.to_dict()
 
-        elif isinstance(obj, CustomValueType):
+        elif isinstance(obj, BaseCustomType):
             return obj.serialize()
 
         elif isinstance(obj, list):
@@ -90,7 +90,7 @@ def _split_docstring(docstring: str) -> Tuple[str, Optional[str]]:
 
 def _parse_attrs_docstrings(docstring: str) -> Optional[Dict[str, str]]:
     """
-    Given a docstring of a SchemaNode, return a dict with descriptions of individual attributes.
+    Given a docstring of a BaseSchema, return a dict with descriptions of individual attributes.
     """
 
     _, attrs_doc = _split_docstring(docstring)
@@ -138,10 +138,10 @@ def _get_properties_schema(typ: Type[Any]) -> Dict[Any, Any]:
 def _describe_type(typ: Type[Any]) -> Dict[Any, Any]:
     # pylint: disable=too-many-branches
 
-    if inspect.isclass(typ) and issubclass(typ, SchemaNode):
+    if inspect.isclass(typ) and issubclass(typ, BaseSchema):
         return typ.json_schema(include_schema_definition=False)
 
-    elif inspect.isclass(typ) and issubclass(typ, CustomValueType):
+    elif inspect.isclass(typ) and issubclass(typ, BaseCustomType):
         return typ.json_schema()
 
     elif is_none_type(typ):
@@ -170,10 +170,10 @@ def _describe_type(typ: Type[Any]) -> Dict[Any, Any]:
     elif is_dict(typ):
         key, val = get_generic_type_arguments(typ)
 
-        if inspect.isclass(key) and issubclass(key, CustomValueType):
+        if inspect.isclass(key) and issubclass(key, BaseCustomType):
             assert (
-                key.__str__ is not CustomValueType.__str__
-            ), "To support derived 'CustomValueType', __str__ must be implemented."
+                key.__str__ is not BaseCustomType.__str__
+            ), "To support derived 'BaseCustomType', __str__ must be implemented."
         else:
             assert key == str, "We currently do not support any other keys then strings"
 
@@ -289,15 +289,15 @@ def _validated_object_type(
     # int
     elif cls == int:
         # we don't want to make an int out of anything else than other int
-        # except for CustomValueType class instances
-        if is_obj_type(obj, int) or isinstance(obj, CustomValueType):
+        # except for BaseCustomType class instances
+        if is_obj_type(obj, int) or isinstance(obj, BaseCustomType):
             return int(obj)
         raise DataValidationError(f"expected int, found {type(obj)}", object_path)
 
     # str
     elif cls == str:
         # we are willing to cast any primitive value to string, but no compound values are allowed
-        if is_obj_type(obj, (str, float, int)) or isinstance(obj, CustomValueType):
+        if is_obj_type(obj, (str, float, int)) or isinstance(obj, BaseCustomType):
             return str(obj)
         elif is_obj_type(obj, bool):
             raise DataValidationError(
@@ -358,8 +358,8 @@ def _validated_object_type(
     elif is_obj_type(obj, cls):
         return obj
 
-    # CustomValueType subclasses
-    elif inspect.isclass(cls) and issubclass(cls, CustomValueType):
+    # BaseCustomType subclasses
+    elif inspect.isclass(cls) and issubclass(cls, BaseCustomType):
         if isinstance(obj, cls):
             # if we already have a custom value type, just pass it through
             return obj
@@ -367,13 +367,13 @@ def _validated_object_type(
             # no validation performed, the implementation does it in the constuctor
             return cls(obj, object_path=object_path)
 
-    # nested SchemaNode subclasses
-    elif inspect.isclass(cls) and issubclass(cls, SchemaNode):
+    # nested BaseSchema subclasses
+    elif inspect.isclass(cls) and issubclass(cls, BaseSchema):
         # we should return DataParser, we expect to be given a dict,
         # because we can construct a DataParser from it
-        if isinstance(obj, (dict, SchemaNode)):
+        if isinstance(obj, (dict, BaseSchema)):
             return cls(obj, object_path=object_path)  # type: ignore
-        raise DataValidationError(f"expected 'dict' or 'SchemaNode' object, found '{type(obj)}'", object_path)
+        raise DataValidationError(f"expected 'dict' or 'BaseSchema' object, found '{type(obj)}'", object_path)
 
     # if the object matches, just pass it through
     elif inspect.isclass(cls) and isinstance(obj, cls):
@@ -388,7 +388,7 @@ def _validated_object_type(
         )
 
 
-TSource = Union[NoneType, ParsedTree, "SchemaNode", Dict[str, Any]]
+TSource = Union[NoneType, ParsedTree, "BaseSchema", Dict[str, Any]]
 
 
 def _create_untouchable(name: str) -> object:
@@ -402,7 +402,7 @@ def _create_untouchable(name: str) -> object:
     return _Untouchable()
 
 
-class SchemaNode(Serializable):
+class BaseSchema(Serializable):
     """
     Class for modelling configuration schema. It somewhat resembles standard dataclasses with additional
     functionality:
@@ -411,7 +411,7 @@ class SchemaNode(Serializable):
     * data conversion
 
     To create an instance of this class, you have to provide source data in the form of dict-like object.
-    Generally, we expect `ParsedTree`, raw dict or another `SchemaNode` instance. The provided data object
+    Generally, we expect `ParsedTree`, raw dict or another `BaseSchema` instance. The provided data object
     is traversed, transformed and validated before assigned to the appropriate fields.
 
     Fields (attributes)
@@ -420,17 +420,17 @@ class SchemaNode(Serializable):
     The fields (or attributes) of the class are defined the same way as in a dataclass by creating a class-level
     type-annotated fields. An example of that is:
 
-    class A(SchemaNode):
+    class A(BaseSchema):
         awesome_number: int
 
-    If your `SchemaNode` instance has a field with type of a SchemaNode, its value is recursively created
-    from the nested input data. This way, you can specify a complex tree of SchemaNode's and use the root
-    SchemaNode to create instance of everything.
+    If your `BaseSchema` instance has a field with type of a BaseSchema, its value is recursively created
+    from the nested input data. This way, you can specify a complex tree of BaseSchema's and use the root
+    BaseSchema to create instance of everything.
 
     Transformation
     ==============
 
-    You can provide the SchemaNode class with a field and a function with the same name, but starting with
+    You can provide the BaseSchema class with a field and a function with the same name, but starting with
     underscore ('_'). For example, you could have field called `awesome_number` and function called
     `_awesome_number(self, source)`. The function takes one argument - the source data (optionally with self,
     but you are not supposed to touch that). It can read any data from the source object and return a value of
@@ -439,7 +439,7 @@ class SchemaNode(Serializable):
 
     Using this, you can convert any input values into any type and field you want. To make the conversion easier
     to write, you could also specify a special class variable called `_LAYER` pointing to another
-    SchemaNode class. This causes the source object to be first parsed as the specified SchemaNode and after that
+    BaseSchema class. This causes the source object to be first parsed as the specified BaseSchema and after that
     used a source for this class. This therefore allows nesting of transformation functions.
 
     Validation
@@ -465,7 +465,7 @@ class SchemaNode(Serializable):
     See tests/utils/test_modelling.py for example usage.
     """
 
-    _LAYER: Optional[Type["SchemaNode"]] = None
+    _LAYER: Optional[Type["BaseSchema"]] = None
 
     def _assign_default(self, name: str, python_type: Any, object_path: str) -> None:
         cls = self.__class__
@@ -477,7 +477,7 @@ class SchemaNode(Serializable):
         value = _validated_object_type(python_type, value, object_path=f"{object_path}/{name}")
         setattr(self, name, value)
 
-    def _assign_fields(self, source: Union[ParsedTree, "SchemaNode", NoneType], object_path: str) -> Set[str]:
+    def _assign_fields(self, source: Union[ParsedTree, "BaseSchema", NoneType], object_path: str) -> Set[str]:
         """
         Order of assignment:
           1. all direct assignments
@@ -540,9 +540,9 @@ class SchemaNode(Serializable):
             source = ParsedTree(source)
 
         # save source
-        self._source: Union[ParsedTree, SchemaNode] = source
+        self._source: Union[ParsedTree, BaseSchema] = source
 
-        # construct lower level schema node first if configured to do so
+        # construct lower level schema first if configured to do so
         if self._LAYER is not None:
             source = self._LAYER(source, object_path=object_path)  # pylint: disable=not-callable
 
@@ -550,7 +550,7 @@ class SchemaNode(Serializable):
         used_keys = self._assign_fields(source, object_path)
 
         # check for unused keys in the source object
-        if source and not isinstance(source, SchemaNode):
+        if source and not isinstance(source, BaseSchema):
             unused = source.keys() - used_keys
             if len(unused) > 0:
                 keys = ", ".join((f"'{u}'" for u in unused))
@@ -566,7 +566,7 @@ class SchemaNode(Serializable):
             raise DataValidationError(e.args[0] if len(e.args) > 0 else "Validation error", object_path) from e
 
     def get_unparsed_data(self) -> ParsedTree:
-        if isinstance(self._source, SchemaNode):
+        if isinstance(self._source, BaseSchema):
             return self._source.get_unparsed_data()
         else:
             return self._source
@@ -619,7 +619,7 @@ class SchemaNode(Serializable):
         return True
 
     @classmethod
-    def json_schema(cls: Type["SchemaNode"], include_schema_definition: bool = True) -> Dict[Any, Any]:
+    def json_schema(cls: Type["BaseSchema"], include_schema_definition: bool = True) -> Dict[Any, Any]:
         if cls._LAYER is not None:
             return cls._LAYER.json_schema(include_schema_definition=include_schema_definition)
 
index e89711eceb5599e730491434100a92852294e673..b63520bd0beb08ca481559f685d9648251659dd8 100644 (file)
@@ -22,7 +22,7 @@ from knot_resolver_manager.datamodel.types import (
     SizeUnit,
     TimeUnit,
 )
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 from knot_resolver_manager.utils.modeling.exceptions import DataValidationError
 
 
@@ -73,7 +73,7 @@ def test_time_unit_invalid(val: Any):
 
 
 def test_parsing_units():
-    class TestSchema(SchemaNode):
+    class TestSchema(BaseSchema):
         size: SizeUnit
         time: TimeUnit
 
@@ -85,7 +85,7 @@ def test_parsing_units():
 
 
 def test_checked_path():
-    class TestSchema(SchemaNode):
+    class TestSchema(BaseSchema):
         p: CheckedPath
 
     assert str(TestSchema({"p": "/tmp"}).p) == "/tmp"
index b8dfcae7b55da2ffd677caafefb862d7c0b0fbe5..f25de7f0fc2d7b3fc5e5e22d2dd9ed6ee90a0fd4 100644 (file)
@@ -4,19 +4,19 @@ import pytest
 from pytest import raises
 from typing_extensions import Literal
 
-from knot_resolver_manager.utils.modeling import SchemaNode, parse_json, parse_yaml
+from knot_resolver_manager.utils.modeling import BaseSchema, parse_json, parse_yaml
 from knot_resolver_manager.utils.modeling.exceptions import DataDescriptionError, DataValidationError
 
 
-class _TestBool(SchemaNode):
+class _TestBool(BaseSchema):
     v: bool
 
 
-class _TestInt(SchemaNode):
+class _TestInt(BaseSchema):
     v: int
 
 
-class _TestStr(SchemaNode):
+class _TestStr(BaseSchema):
     v: str
 
 
@@ -54,8 +54,8 @@ def test_parsing_str_invalid():
 
 
 @pytest.mark.parametrize("typ,val", [(_TestInt, 5), (_TestBool, False), (_TestStr, "test")])
-def test_parsing_nested(typ: Type[SchemaNode], val: Any):
-    class UpperSchema(SchemaNode):
+def test_parsing_nested(typ: Type[BaseSchema], val: Any):
+    class UpperSchema(BaseSchema):
         l: typ
 
     yaml = f"""
@@ -68,7 +68,7 @@ l:
 
 
 def test_parsing_simple_compound_types():
-    class TestSchema(SchemaNode):
+    class TestSchema(BaseSchema):
         l: List[int]
         d: Dict[str, str]
         t: Tuple[str, int]
@@ -97,7 +97,7 @@ t:
 
 
 def test_parsing_nested_compound_types():
-    class TestSchema(SchemaNode):
+    class TestSchema(BaseSchema):
         i: int
         o: Optional[Dict[str, str]]
 
@@ -119,15 +119,15 @@ o:
 
 
 def test_partial_mutations():
-    class InnerSchema(SchemaNode):
+    class InnerSchema(BaseSchema):
         size: int = 5
 
-    class ConfPreviousSchema(SchemaNode):
+    class ConfPreviousSchema(BaseSchema):
         workers: Union[Literal["auto"], int] = 1
         lua_config: Optional[str] = None
         inner: InnerSchema = InnerSchema()
 
-    class ConfSchema(SchemaNode):
+    class ConfSchema(BaseSchema):
         _LAYER = ConfPreviousSchema
 
         workers: int
@@ -179,7 +179,7 @@ def test_partial_mutations():
 
 
 def test_dash_conversion():
-    class TestSchema(SchemaNode):
+    class TestSchema(BaseSchema):
         awesome_field: Dict[str, str]
 
     yaml = """
@@ -192,7 +192,7 @@ awesome-field:
 
 
 def test_eq():
-    class B(SchemaNode):
+    class B(BaseSchema):
         a: _TestInt
         field: str
 
@@ -207,7 +207,7 @@ def test_eq():
 
 
 def test_docstring_parsing_valid():
-    class NormalDescription(SchemaNode):
+    class NormalDescription(BaseSchema):
         """
         Does nothing special
         Really
@@ -216,7 +216,7 @@ def test_docstring_parsing_valid():
     desc = NormalDescription.json_schema()
     assert desc["description"] == "Does nothing special\nReally"
 
-    class FieldsDescription(SchemaNode):
+    class FieldsDescription(BaseSchema):
         """
         This is an awesome test class
         ---
@@ -232,14 +232,14 @@ def test_docstring_parsing_valid():
     assert schema["properties"]["field"]["description"] == "This field does nothing interesting"
     assert schema["properties"]["value"]["description"] == "Neither does this"
 
-    class NoDescription(SchemaNode):
+    class NoDescription(BaseSchema):
         nothing: str
 
     _ = NoDescription.json_schema()
 
 
 def test_docstring_parsing_invalid():
-    class AdditionalItem(SchemaNode):
+    class AdditionalItem(BaseSchema):
         """
         This class is wrong
         ---
@@ -252,7 +252,7 @@ def test_docstring_parsing_invalid():
     with raises(DataDescriptionError):
         _ = AdditionalItem.json_schema()
 
-    class WrongDescription(SchemaNode):
+    class WrongDescription(BaseSchema):
         """
         This class is wrong
         ---
index 6b9a246af636ca14da7898f668164b0df21dc609..281f03a8e895aa53c55bec2026b362e529e32da6 100644 (file)
@@ -3,7 +3,7 @@ from typing import Any, Dict, List, Tuple, Union
 import pytest
 from typing_extensions import Literal
 
-from knot_resolver_manager.utils.modeling import SchemaNode
+from knot_resolver_manager.utils.modeling import BaseSchema
 from knot_resolver_manager.utils.modeling.types import is_list, is_literal
 
 types = [
@@ -13,7 +13,7 @@ types = [
     Dict[Any, Any],
     Tuple[Any, Any],
     Union[str, int],
-    SchemaNode,
+    BaseSchema,
 ]
 literal_types = [Literal[5], Literal["test"], Literal[False]]