Coverage for bioimageio/spec/_internal/validated_string.py: 80%

25 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2025-02-05 13:53 +0000

1from typing import Any, ClassVar, Type 

2 

3from pydantic import GetCoreSchemaHandler, GetJsonSchemaHandler, RootModel 

4from pydantic.json_schema import JsonSchemaValue 

5from pydantic_core.core_schema import ( 

6 CoreSchema, 

7 no_info_after_validator_function, 

8) 

9from typing_extensions import Self 

10 

11 

12class ValidatedString(str): 

13 root_model: ClassVar[Type[RootModel[Any]]] = RootModel[str] 

14 """the pydantic root model to validate the string""" 

15 # TODO: should we use a TypeAdapter instead? 

16 # TODO: with future py version: RootModel[Any] -> RootModel[str | "literal string type"] 

17 _validated: Any # pyright: ignore[reportUninitializedInstanceVariable] # initalized in __new__ 

18 

19 def __new__(cls, object: object): 

20 self = super().__new__(cls, object) 

21 self._validated = cls.root_model.model_validate(str(self)).root 

22 return self._after_validator() 

23 

24 def _after_validator(self) -> Self: 

25 """add validation after the `root_model`""" 

26 return self 

27 

28 @classmethod 

29 def __get_pydantic_core_schema__( 

30 cls, source_type: Any, handler: GetCoreSchemaHandler 

31 ) -> CoreSchema: 

32 return no_info_after_validator_function(cls, handler(str)) 

33 

34 @classmethod 

35 def __get_pydantic_json_schema__( 

36 cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler 

37 ) -> JsonSchemaValue: 

38 json_schema = cls.root_model.model_json_schema(mode=handler.mode) 

39 json_schema["title"] = cls.__name__.strip("_") 

40 if cls.__doc__: 

41 json_schema["description"] = cls.__doc__ 

42 

43 return json_schema