From d885a3cd8ef9d68d82774522eafff812f45b08a2 Mon Sep 17 00:00:00 2001 From: Jose Tomas Robles Hahn Date: Thu, 24 Oct 2024 23:08:58 -0300 Subject: [PATCH] fix(extras): Pydantic `Rut` type regex is not compliant with JSON Schema The regular expression used to validate RUTs in `_RutPydanticAnnotation` results in Pydantic generating an invalid JSON Schema because the regex uses named groups, which are not supported by the JavaScript regular expression syntax used by JSON Schema (and OpenAPI). --- src/cl_sii/extras/pydantic_types.py | 22 ++++++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/src/cl_sii/extras/pydantic_types.py b/src/cl_sii/extras/pydantic_types.py index a55a2b03..cd0f3a89 100644 --- a/src/cl_sii/extras/pydantic_types.py +++ b/src/cl_sii/extras/pydantic_types.py @@ -4,8 +4,9 @@ from __future__ import annotations +import re import sys -from typing import Any +from typing import Any, ClassVar, Pattern if sys.version_info[:2] >= (3, 9): @@ -74,6 +75,21 @@ class _RutPydanticAnnotation: b'"78773510-K"' """ + RUT_CANONICAL_STRICT_REGEX: ClassVar[Pattern] = re.compile( + re.sub( + pattern=r'\?P<\w+>', + repl='', + string=cl_sii.rut.constants.RUT_CANONICAL_STRICT_REGEX.pattern, + ) + ) + """ + RUT (strict) regex for canonical format, without named groups. + + .. warning:: + JSON Schema and OpenAPI use the regular expression syntax from + JavaScript (ECMA 262), which does not support Python’s named groups. + """ + @classmethod def __get_pydantic_core_schema__( cls, source_type: Any, handler: pydantic.GetCoreSchemaHandler @@ -83,9 +99,7 @@ def validate_from_str(value: str) -> cl_sii.rut.Rut: from_str_schema = pydantic_core.core_schema.chain_schema( [ - pydantic_core.core_schema.str_schema( - pattern=cl_sii.rut.constants.RUT_CANONICAL_STRICT_REGEX.pattern - ), + pydantic_core.core_schema.str_schema(pattern=cls.RUT_CANONICAL_STRICT_REGEX), pydantic_core.core_schema.no_info_plain_validator_function(validate_from_str), ] )