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

26 statements  

« prev     ^ index     » next       coverage.py v7.8.0, created at 2025-04-02 14:21 +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 _validated = cls.root_model.model_validate(object).root 

21 self = super().__new__(cls, _validated) 

22 self._validated = _validated 

23 return self._after_validator() 

24 

25 def _after_validator(self) -> Self: 

26 """add validation after the `root_model`""" 

27 return self 

28 

29 @classmethod 

30 def __get_pydantic_core_schema__( 

31 cls, source_type: Any, handler: GetCoreSchemaHandler 

32 ) -> CoreSchema: 

33 return no_info_after_validator_function(cls, handler(str)) 

34 

35 @classmethod 

36 def __get_pydantic_json_schema__( 

37 cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler 

38 ) -> JsonSchemaValue: 

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

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

41 if cls.__doc__: 

42 json_schema["description"] = cls.__doc__ 

43 

44 return json_schema