Debian Codegraph @

tests/utils.py

raw
1 from __future__ import annotations
2
3 import os
4 import traceback
5 import contextlib
6 from typing import Any, TypeVar, Iterator, Sequence, cast
7 from datetime import date, datetime
8 from typing_extensions import Literal, get_args, get_origin, assert_type
9
10 from anthropic._types import Omit, NoneType
11 from anthropic._utils import (
12 is_dict,
13 is_list,
14 is_list_type,
15 is_union_type,
16 extract_type_arg,
17 is_sequence_type,
18 is_annotated_type,
19 is_type_alias_type,
20 )
21 from anthropic._compat import PYDANTIC_V1, field_outer_type, get_model_fields
22 from anthropic._models import BaseModel
23
24 BaseModelT = TypeVar("BaseModelT", bound=BaseModel)
25
26
27 def assert_matches_model(model: type[BaseModelT], value: BaseModelT, *, path: list[str]) -> bool:
28 for name, field in get_model_fields(model).items():
29 field_value = getattr(value, name)
30 if PYDANTIC_V1:
31 # in v1 nullability was structured differently
32 # https://docs.pydantic.dev/2.0/migration/#required-optional-and-nullable-fields
33 allow_none = getattr(field, "allow_none", False)
34 else:
35 allow_none = False
36
37 assert_matches_type(
38 field_outer_type(field),
39 field_value,
40 path=[*path, name],
41 allow_none=allow_none,
42 )
43
44 return True
45
46
47 # Note: the `path` argument is only used to improve error messages when `--showlocals` is used
48 def assert_matches_type(
49 type_: Any,
50 value: object,
51 *,
52 path: list[str],
53 allow_none: bool = False,
54 ) -> None:
55 if is_type_alias_type(type_):
56 type_ = type_.__value__
57
58 # unwrap `Annotated[T, ...]` -> `T`
59 if is_annotated_type(type_):
60 type_ = extract_type_arg(type_, 0)
61
62 if allow_none and value is None:
63 return
64
65 if type_ is None or type_ is NoneType:
66 assert value is None
67 return
68
69 origin = get_origin(type_) or type_
70
71 if is_list_type(type_):
72 return _assert_list_type(type_, value)
73
74 if is_sequence_type(type_):
75 assert isinstance(value, Sequence)
76 inner_type = get_args(type_)[0]
77 for entry in value: # type: ignore
78 assert_type(inner_type, entry) # type: ignore
79 return
80
81 if origin == str:
82 assert isinstance(value, str)
83 elif origin == int:
84 assert isinstance(value, int)
85 elif origin == bool:
86 assert isinstance(value, bool)
87 elif origin == float:
88 assert isinstance(value, float)
89 elif origin == bytes:
90 assert isinstance(value, bytes)
91 elif origin == datetime:
92 assert isinstance(value, datetime)
93 elif origin == date:
94 assert isinstance(value, date)
95 elif origin == object:
96 # nothing to do here, the expected type is unknown
97 pass
98 elif origin == Literal:
99 assert value in get_args(type_)
100 elif origin == dict:
101 assert is_dict(value)
102
103 args = get_args(type_)
104 key_type = args[0]
105 items_type = args[1]
106
107 for key, item in value.items():
108 assert_matches_type(key_type, key, path=[*path, "<dict key>"])
109 assert_matches_type(items_type, item, path=[*path, "<dict item>"])
110 elif is_union_type(type_):
111 variants = get_args(type_)
112
113 try:
114 none_index = variants.index(type(None))
115 except ValueError:
116 pass
117 else:
118 # special case Optional[T] for better error messages
119 if len(variants) == 2:
120 if value is None:
121 # valid
122 return
123
124 return assert_matches_type(type_=variants[not none_index], value=value, path=path)
125
126 for i, variant in enumerate(variants):
127 try:
128 assert_matches_type(variant, value, path=[*path, f"variant {i}"])
129 return
130 except AssertionError:
131 traceback.print_exc()
132 continue
133
134 raise AssertionError("Did not match any variants")
135 elif issubclass(origin, BaseModel):
136 assert isinstance(value, type_)
137 assert assert_matches_model(type_, cast(Any, value), path=path)
138 else:
139 assert None, f"Unhandled field type: {type_}"
140
141
142 def _assert_list_type(type_: type[object], value: object) -> None:
143 assert is_list(value)
144
145 inner_type = get_args(type_)[0]
146 for entry in value:
147 assert_type(inner_type, entry) # type: ignore
148
149
150 @contextlib.contextmanager
151 def update_env(**new_env: str | Omit) -> Iterator[None]:
152 old = os.environ.copy()
153
154 try:
155 for name, value in new_env.items():
156 if isinstance(value, Omit):
157 os.environ.pop(name, None)
158 else:
159 os.environ[name] = value
160
161 yield None
162 finally:
163 os.environ.clear()
164 os.environ.update(old)